有人知道一种方法(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'
}
]
}
只需简单的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);
您正在寻找_.groupBy()。
如果需要,从对象中删除分组的属性应该很简单:
Const cars = [{
“做”:“奥迪”,
“模型”:“r8”,
“年”:“2012”
},{
“做”:“奥迪”,
“模型”:“生活费”,
“年”:“2013”
},{
“做”:“福特”,
“模型”:“野马”,
“年”:“2012”
},{
“做”:“福特”,
“模型”:“融合”,
“年”:“2015”
},{
“做”:“克钦独立军”,
“模型”:“最佳状态”,
“年”:“2012”
});
Const分组= _。groupBy(cars, car => car.make);
console.log(分组);
< script src = " https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js " > < /脚本>
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' ] } ]
我喜欢写它没有依赖/复杂性,只是纯粹的简单js。
const mp = {}
const cars = [
{
model: 'Imaginary space craft SpaceX model',
year: '2025'
},
{
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'
}
]
cars.forEach(c => {
if (!c.make) return // exit (maybe add them to a "no_make" category)
if (!mp[c.make]) mp[c.make] = [{ model: c.model, year: c.year }]
else mp[c.make].push({ model: c.model, year: c.year })
})
console.log(mp)