有人知道一种方法(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'
        }
    ]
}

当前回答

Prototype version using ES6 as well. Basically this uses the reduce function to pass in an accumulator and current item, which then uses this to build your "grouped" arrays based on the passed in key. the inner part of the reduce may look complicated but essentially it is testing to see if the key of the passed in object exists and if it doesn't then create an empty array and append the current item to that newly created array otherwise using the spread operator pass in all the objects of the current key array and append current item. Hope this helps someone!.

Array.prototype.groupBy = function(k) {
  return this.reduce((acc, item) => ((acc[item[k]] = [...(acc[item[k]] || []), item]), acc),{});
};

const projs = [
  {
    project: "A",
    timeTake: 2,
    desc: "this is a description"
  },
  {
    project: "B",
    timeTake: 4,
    desc: "this is a description"
  },
  {
    project: "A",
    timeTake: 12,
    desc: "this is a description"
  },
  {
    project: "B",
    timeTake: 45,
    desc: "this is a description"
  }
];

console.log(projs.groupBy("project"));

其他回答

简单的for循环也可以实现:

 const result = {};

 for(const {make, model, year} of cars) {
   if(!result[make]) result[make] = [];
   result[make].push({ model, year });
 }

下面是一个受到Java中的collections . groupingby()启发的解决方案:

function groupingBy(list, keyMapper) { 返回列表。reduce((accummalatorMap, currentValue) => { const key = keyMapper(currentValue); 如果(! accummalatorMap.has(键)){ accummalatorMap。集(关键,[currentValue]); }其他{ accummalatorMap。集(键,accummalatorMap.get(关键).push (currentValue)); } 返回accummalatorMap; }, new Map()); }

这将给出一个Map对象。

/ /使用 const cars = groupingBy(cars, car => car.make);

letfinaldata=[]

let data =[{id:1,name:"meet"},{id:2,name:"raj"},{id:1,name:"hari"},{id:3,name:"hari"},{id:2,name:"ram"}]

data = data.map((item)=> 
{
    return {...item,
        name: [item.name]
    }
}) // Converting the name key from string to array


let temp = [];

for(let i =0 ;i<data.length;i++)
{
    const index = temp.indexOf(data[i].id) // Checking if the object id is already present
    if(index>=0)
    {
        letfinaldata[index].name = [...letfinaldata[index].name,...data[i].name] // If present then append the name to the name of that object
    }
    else{
        temp.push(data[i].id); // Push the checked object id
        letfinaldata.push({...data[i]}) // Push the object
    }
}

console.log(letfinaldata)

输出

[ { id: 1, name: [ 'meet', 'hari' ] },
  { id: 2, name: [ 'raj', 'ram' ] },
  { id: 3, name: [ 'hari' ] } ]

你也可以像这样使用数组#forEach()方法:

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' }]; let newcars = {} cars.forEach(car => { newcars[car.make] ? // check if that array exists or not in newcars object newcars[car.make].push({model: car.model, year: car.year}) // just push : (newcars[car.make] = [], newcars[car.make].push({model: car.model, year: car.year})) // create a new array and push }) console.log(newcars);

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

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