javascript-根据属性将对象数组分成单独的数组

说我有一个像这样的数组:

var arr = [
    {type:"orange", title:"First"},
    {type:"orange", title:"Second"},
    {type:"banana", title:"Third"},
    {type:"banana", title:"Fourth"}
];

我希望将其拆分为具有相同类型对象的数组,以便:

[{type:"orange", title:"First"},
{type:"orange", title:"Second"}]

[{type:"banana", title:"Third"},
{type:"banana", title:"Fourth"}]

但是我想一般地这样做,所以没有if语句指定橙色或香蕉

// not like this
for (prop in arr){
    if (arr[prop] === "banana"){
       //add to new array
    }
}

有什么想法吗? JQuery和Underscore都是要使用的选项。

Evan asked 2020-08-06T10:35:08Z
5个解决方案
40 votes

JQuery和Underscore都是要使用的选项。

Underscore的groupBy完全可以满足您的需求。

_.groupBy(arr, "type")
Bergi answered 2020-08-06T10:35:17Z
36 votes

对于Array.reduce(...),这是一项容易的工作:

function groupBy(arr, property) {
  return arr.reduce(function(memo, x) {
    if (!memo[x[property]]) { memo[x[property]] = []; }
    memo[x[property]].push(x);
    return memo;
  }, {});
}

var o = groupBy(arr, 'type'); // => {orange:[...], banana:[...]}
o.orange; // => [{"type":"orange","title":"First"},{"type":"orange","title":"Second"}]
o.banana; // => [{"type":"banana","title":"Third"},{"type":"banana","title":"Fourth"}]

当然,如果您的目标浏览器不支持ECMAScript 262第5版,则您必须自己实现“减少”,或使用polyfill库,或选择其他答案。

[更新]以下是适用于任何版本的JavaScript的解决方案:

function groupBy2(xs, prop) {
  var grouped = {};
  for (var i=0; i<xs.length; i++) {
    var p = xs[i][prop];
    if (!grouped[p]) { grouped[p] = []; }
    grouped[p].push(xs[i]);
  }
  return grouped;
}
maerics answered 2020-08-06T10:35:46Z
11 votes

这假定了一个对象数组:

function groupBy(array, property) {
    var hash = {};
    for (var i = 0; i < array.length; i++) {
        if (!hash[array[i][property]]) hash[array[i][property]] = [];
        hash[array[i][property]].push(array[i]);
    }
    return hash;
}

groupBy(arr,'type')  // Object {orange: Array[2], banana: Array[2]}
groupBy(arr,'title') // Object {First: Array[1], Second: Array[1], Third: Array[1], Fourth: Array[1]}
Shmiddty answered 2020-08-06T10:36:06Z
9 votes

只需建立一个字典即可根据其标题保存对象。 您可以这样做:

js

var arr = [
{type:"orange", title:"First"},
 {type:"orange", title:"Second"},
 {type:"banana", title:"Third"},
 {type:"banana", title:"Fourth"}
];
var sorted = {};
for( var i = 0, max = arr.length; i < max ; i++ ){
 if( sorted[arr[i].type] == undefined ){
  sorted[arr[i].type] = [];
 }
 sorted[arr[i].type].push(arr[i]);
}
console.log(sorted["orange"]);
console.log(sorted["banana"]);

js字段,但:“ htp:/// js字段。t/ YJn M6 /”

Travis J answered 2020-08-06T10:36:34Z
2 votes

打字稿版本。

/**
* Group object array by property
 * Example, groupBy(array, ( x: Props ) => x.id );
 * @param array
 * @param property
 */
export const groupBy = <T>(array: Array<T>, property: (x: T) => string): { [key: string]: Array<T> } =>
  array.reduce((memo: { [key: string]: Array<T> }, x: T) => {
    if (!memo[property(x)]) {
      memo[property(x)] = [];
    }
    memo[property(x)].push(x);
    return memo;
  }, {});

export default groupBy;
denolsson answered 2020-08-06T10:36:54Z
translate from https://stackoverflow.com:/questions/14696326/break-array-of-objects-into-separate-arrays-based-on-a-property