根据属性将对象数组分解为单独的数组 [英] break array of objects into separate arrays based on a property

查看:58
本文介绍了根据属性将对象数组分解为单独的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Say I have an array like this:

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.

Underscore 的 groupBy 正是您所需要的.

Underscore's groupBy does exactly what you need.

_.groupBy(arr, "type")

这篇关于根据属性将对象数组分解为单独的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆