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

const 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分组:

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

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

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

当前回答

根据@Jonas_Wilms的回答,如果你不想输入所有的字段:

    var result = {};

    for ( let { first_field, ...fields } of your_data ) 
    { 
       result[first_field] = result[first_field] || [];
       result[first_field].push({ ...fields }); 
    }

我没有做任何基准测试,但我相信使用for循环会比这个答案中建议的任何方法都更有效。

其他回答

我用REAL GROUP BY作为JS数组的例子和这个任务完全一样

const inputArray = [ { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" }, { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" }, { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" }, { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" }, { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" } ]; var outObject = inputArray.reduce(function(a, e) { // GROUP BY estimated key (estKey), well, may be a just plain key // a -- Accumulator result object // e -- sequentally checked Element, the Element that is tested just at this itaration // new grouping name may be calculated, but must be based on real value of real field let estKey = (e['Phase']); (a[estKey] ? a[estKey] : (a[estKey] = null || [])).push(e); return a; }, {}); console.log(outObject);

这是一个通用函数,将返回Array groupBy自己的键。

const getSectionListGroupedByKey = < T > ( property: keyof T, List: Array < T > ): Array < { title: T[keyof T];data: Array < T > } > => { const sectionList: Array < { title: T[keyof T];data: Array < T > } > = []; if (!property || !List ? .[0] ? .[property]) { return []; } const groupedTxnListMap: Map < T[keyof T], Array < T >> = List.reduce((acc, cv) => { const keyValue: T[keyof T] = cv[property]; if (acc.has(keyValue)) { acc.get(keyValue) ? .push(cv); } else { acc.set(keyValue, [cv]); } return acc; }, new Map < T[keyof T], Array < T >> ()); groupedTxnListMap.forEach((value, key) => { sectionList.push({ title: key, data: value }); }); return sectionList; }; // Example const 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' }, ]; const result = getSectionListGroupedByKey('make', cars); console.log('result: ', result)

只需简单的forEach循环就可以在这里工作,不需要任何库

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' }, ]; let ObjMap ={}; cars.forEach(element => { var makeKey = element.make; if(!ObjMap[makeKey]) { ObjMap[makeKey] = []; } ObjMap[makeKey].push({ model: element.model, year: element.year }); }); console.log(ObjMap);

您可以尝试在调用per iteration的函数中修改对象_。groupBy func。 注意,源数组改变了它的元素!

var res = _.groupBy(cars,(car)=>{
    const makeValue=car.make;
    delete car.make;
    return makeValue;
})
console.log(res);
console.log(cars);

我制定了一个基准测试不使用外部库的每个解决方案的性能。

JSBen.ch

由@Nina Scholz发布的reduce()选项似乎是最佳选项。