基于属性将对象数组分成单独的数组 [英] break array of objects into separate arrays based on a property
本文介绍了基于属性将对象数组分成单独的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有这样的数组:
var arr = [
{type:"orange", title:"First"},
{type:"orange", title:"Second"},
{type:"banana", title:"Third"},
{type:"banana", title:"Fourth"}
];
我希望将它拆分成具有相同类型的对象的数组:
and I want this to be split up into arrays that have objects which have same type so:
[{type:"orange", title:"First"},
{type:"orange", title:"Second"}]
[{type:"banana", title:"Third"},
{type:"banana", title:"Fourth"}]
但我想这样做,所以没有if语句指定橙色或香蕉
But I want to do this generically so not having an if statement that specifies orange or banana
// not like this
for (prop in arr){
if (arr[prop] === "banana"){
//add to new array
}
}
思考? JQuery和Underscore都是可以使用的选项。
Thoughts? JQuery and Underscore are both options to use.
推荐答案
JQuery和Underscore都是可以使用的选项。
JQuery and Underscore are both options to use.
下划线的 groupBy
完全符合您的要求。
Underscore's groupBy
does exactly what you need.
_.groupBy(arr, "type")
这篇关于基于属性将对象数组分成单独的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文