将对象数组根据属性拆分为多个单独的数组

89

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

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
12个回答

0

对@Watchmaker的答案进行了小修改,以返回数组而不是对象:

function groupBy(arr, key) {
  return arr.reduce((acc, cur) => {
    acc[cur[key]] = [...acc[cur[key]] || [], cur];
    return acc;
  }, []).filter(Boolean);
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接