打破对象数组基于一个属性单独的阵列(break array of objects into sepa

2019-07-19 06:16发布

说我有一个这样的数组:

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和下划线都选择使用。

Answer 1:

jQuery和下划线都选择使用。

下划线的groupBy不正是你所需要的。

_.groupBy(arr, "type")


Answer 2:

这是一件容易的事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"}]

当然,如果你的目标浏览器(S)不支持的ECMAScript 262第5版,那么你就必须实现“降低”自己,或使用填充工具库,或选择另一个答案。

[更新]这是应该使用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;
}


Answer 3:

只是建立持有根据他们的标题对象的字典。 你可以做这样的:

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"]);

的jsfiddle演示: http://jsfiddle.net/YJnM6/



Answer 4:

这假定对象的数组:

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]}


Answer 5:

打字稿版本。

/**
* 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;


文章来源: break array of objects into separate arrays based on a property