如何按键对对象数组进行分组 [英] How to group an array of objects by key

查看:33
本文介绍了如何按键对对象数组进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道(如果可能的话,也可以使用 lodash)通过对象键对对象数组进行分组,然后根据分组创建新的对象数组的方法吗?例如,我有一个汽车对象数组:

Does anyone know of a (lodash if possible too) way to group an array of objects by an object key then create a new array of objects based on the grouping? For example, I have an array of car objects:

var cars = [
    {
        'make': 'audi',
        'model': 'r8',
        'year': '2012'
    }, {
        'make': 'audi',
        'model': 'rs5',
        'year': '2013'
    }, {
        'make': 'ford',
        'model': 'mustang',
        'year': '2012'
    }, {
        'make': 'ford',
        'model': 'fusion',
        'year': '2015'
    }, {
        'make': 'kia',
        'model': 'optima',
        'year': '2012'
    },
];

我想创建一个由 make 分组的新汽车对象数组:

I want to make a new array of car objects that's grouped by make:

var cars = {
    'audi': [
        {
            'model': 'r8',
            'year': '2012'
        }, {
            'model': 'rs5',
            'year': '2013'
        },
    ],

    'ford': [
        {
            'model': 'mustang',
            'year': '2012'
        }, {
            'model': 'fusion',
            'year': '2015'
        }
    ],

    'kia': [
        {
            'model': 'optima',
            'year': '2012'
        }
    ]
}

推荐答案

Timo 的回答 是我会怎么做.简单的_.groupBy,并允许在分组结构中的对象中有一些重复.

Timo's answer is how I would do it. Simple _.groupBy, and allow some duplications in the objects in the grouped structure.

然而,OP 还要求删除重复的 make 键.如果你想一路走下去:

However the OP also asked for the duplicate make keys to be removed. If you wanted to go all the way:

var grouped = _.mapValues(_.groupBy(cars, 'make'),
                          clist => clist.map(car => _.omit(car, 'make')));

console.log(grouped);

产量:

{ audi:
   [ { model: 'r8', year: '2012' },
     { model: 'rs5', year: '2013' } ],
  ford:
   [ { model: 'mustang', year: '2012' },
     { model: 'fusion', year: '2015' } ],
  kia: 
   [ { model: 'optima', year: '2012' } ] 
}

如果您想使用 Underscore.js 执行此操作,请注意它的 _.mapValues 版本称为 _.mapObject.

If you wanted to do this using Underscore.js, note that its version of _.mapValues is called _.mapObject.

这篇关于如何按键对对象数组进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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