根据属性将对象数组分解为单独的数组

2023-11-21

假设我有一个像这样的数组:

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 都是可以使用的选项。


这对于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 版,那么您必须自己实现“reduce”,或者使用 polyfill 库,或者选择其他答案。

[Update]这是一个适用于任何版本的 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

根据属性将对象数组分解为单独的数组 的相关文章

随机推荐