Javascript 如何按键对对象数组进行分组
是否有人知道(如果可能的话,也可以使用lodash)通过对象键对对象数组进行分组,然后根据分组创建新的对象数组的方法?例如,我有一个汽车对象数组:Javascript 如何按键对对象数组进行分组,javascript,arrays,object,grouping,lodash,Javascript,Arrays,Object,Grouping,Lodash,是否有人知道(如果可能的话,也可以使用lodash)通过对象键对对象数组进行分组,然后根据分组创建新的对象数组的方法?例如,我有一个汽车对象数组: var cars = [ { 'make': 'audi', 'model': 'r8', 'year': '2012' }, { 'make': 'audi', 'model': 'rs5', 'year': '2013' },
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
分组:
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'
}
]
}
您正在寻找的。 如果需要,从对象中删除分组依据的属性应该很简单:
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'};
var grouped=uu.groupBy(汽车,功能(汽车){
返回汽车制造;
});
控制台日志(分组)代码>
在纯Javascript中,可以与对象一起使用
var cars=[{make:'audi',model:'r8',year:'2012'},{make:'audi',model:'rs5',year:'2013'},{make:'ford',model:'mustang',year:'2012'},{make:'kia',model:'optima',year:'2012'},{,
结果=车辆。减少(功能(r,a){
r[a.make]=r[a.make]| | |[];
r[a.make].推(a);
返回r;
},Object.create(null));
控制台日志(结果)代码>
.as控制台包装{max height:100%!important;top:0;}
就是我要做的。简单的。.groupBy
,并允许在分组结构中的对象中进行一些复制
然而,OP还要求删除重复的make
键。如果你想一路走下去:
var group=..mapValues(..groupBy(汽车,'make'),
clist=>clist.map(car=>(car'make'));
控制台日志(分组);
收益率:
{audi:
[{型号:'r8',年份:'2012'},
{型号:'rs5',年份:'2013'}],
福特:
[{车型:'mustang',年份:'2012'},
{型号:'fusion',年份:'2015'}],
起亚:
[{型号:'optima',年份:'2012'}]
}
如果要使用下划线.js执行此操作,请注意其版本的.mapValues
称为.mapObject
,您可以尝试修改函数内的对象,该函数由u.groupBy func每次迭代调用。
请注意,源数组会更改其元素
var res = _.groupBy(cars,(car)=>{
const makeValue=car.make;
delete car.make;
return makeValue;
})
console.log(res);
console.log(cars);
完全没有理由下载第三方库来解决这个简单的问题,就像上面的解决方案所建议的那样
在es6中,通过特定的键
将对象的列表
分组的单行版本:
const groupByKey = (list, key) => list.reduce((hash, obj) => ({...hash, [obj[key]]:( hash[obj[key]] || [] ).concat(obj)}), {})
不使用键过滤对象的较长版本:
函数groupByKey(数组,键){
返回数组
.reduce((散列,对象)=>{
if(obj[key]==未定义)返回哈希;
return Object.assign(散列,{[obj[key]]:(散列[obj[key]]| |[]).concat(obj)})
}, {})
}
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','2012';
console.log(groupByKey(cars,'make'))
这是您自己的groupBy
函数,它是以下代码的概括:
函数groupBy(xs,f){
返回xs.reduce((r,v,i,a,k=f(v))=>((r[k]|(r[k]=[])).push(v,r),{});
}
const cars=[{make:'audi',model:'r8',年份:'2012'},{make:'audi',model:'rs5',年份:'2013'},{make:'ford',model:'mustang',年份:'2012'},{make:'ford',model:'fusion',year:'2015'},{make:'kia',model:'optima年份:'2012'};
const result=groupBy(cars,(c)=>c.make);
控制台日志(结果)代码>您也可以使用如下方法:
const cars=[{make:'audi',model:'r8',year:'2012'},{make:'audi',model:'rs5',year:'2013'},{make:'ford',model:'mustang',year:'2012'},{make:'kia',model:'optima',year:'2012'};
让新车={}
cars.forEach(car=>{
newcars[car.make]?//检查newcars对象中是否存在该数组
新车[car.make].push({model:car.model,year:car.year})//只需推一下
:(新车[car.make]=[],新车[car.make].push({model:car.model,year:car.year}))//创建新数组并推送
})
控制台日志(新车)代码>也可以使用一个简单的for
循环:
const result = {};
for(const {make, model, year} of cars) {
if(!result[make]) result[make] = [];
result[make].push({ model, year });
}
对于JS数组示例,我将把REAL GROUP BY
留给与此任务完全相同的人
const inputArray=[
{阶段:“阶段1”,步骤:“步骤1”,任务:“任务1”,值:“5”},
{阶段:“阶段1”,步骤:“步骤1”,任务:“任务2”,值:“10”},
{阶段:“阶段1”,步骤:“步骤2”,任务:“任务1”,值:“15”},
{阶段:“阶段1”,步骤:“步骤2”,任务:“任务2”,值:“20”},
{阶段:“阶段2”,步骤:“步骤1”,任务:“任务1”,值:“25”},
{阶段:“阶段2”,步骤:“步骤1”,任务:“任务2”,值:“30”},
{阶段:“阶段2”,步骤:“步骤2”,任务:“任务1”,值:“35”},
{阶段:“阶段2”,步骤:“步骤2”,任务:“任务2”,值:“40”}
];
var outObject=inputArray.reduce(函数(a,e){
//按估计键分组(estKey),可能只是一个普通键
//a—累加器结果对象
//e——顺序检查的元素,即在该时间点进行测试的元素
//可以计算新的分组名称,但必须基于实字段的实际值
设estKey=(e['Phase']);
(a[estKey]?a[estKey]:(a[estKey]=null | | |[])。按(e);
返回a;
}, {});
console.log(outObject)代码>创建可重复使用的方法
Array.prototype.groupBy = function(prop) {
return this.reduce(function(groups, item) {
const val = item[prop]
groups[val] = groups[val] || []
groups[val].push(item)
return groups
}, {})
};
然后在下面,您可以根据任何标准进行分组
const groupByMake = cars.groupBy('make');
console.log(groupByMake);
var-cars=[
{
“制造”:“奥迪”,
“型号”:“r8”,
“年份”:“2012”
}, {
“制造”:“奥迪”,
“型号”:“rs5”,
“年份”:“2013”
}, {
“制造”:“福特”,
“模型”:“野马”,
function groupBy(data, property) {
return data.reduce((acc, obj) => {
const key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
groupBy(people, 'age');
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'
},
];
result = cars.reduce((h, car) => Object.assign(h, { [car.make]:( h[car.make] || [] ).concat({model: car.model, year: car.year}) }), {})
console.log(JSON.stringify(result));
{
"audi":[
{
"model":"r8",
"year":"2012"
},
{
"model":"rs5",
"year":"2013"
}
],
"ford":[
{
"model":"mustang",
"year":"2012"
},
{
"model":"fusion",
"year":"2015"
}
],
"kia":[
{
"model":"optima",
"year":"2012"
}
]
}
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':'kia','model':'optima','year':'2033'},
{'make':null,'model':'zen','year':'2012'},
{'make':null,'model':'blue','year':'2017'},
];
result = cars.reduce(function (r, a) {
key = a.make || 'others';
r[key] = r[key] || [];
r[key].push(a);
return r;
}, Object.create(null));
var result = {};
for ( let { first_field, ...fields } of your_data )
{
result[first_field] = result[first_field] || [];
result[first_field].push({ ...fields });
}
const reGroup = (list, key) => {
const newGroup = {};
list.forEach(item => {
const newItem = Object.assign({}, item);
delete newItem[key];
newGroup[item[key]] = newGroup[item[key]] || [];
newGroup[item[key]].push(newItem);
});
return newGroup;
};
const animals = [
{
type: 'dog',
breed: 'puddle'
},
{
type: 'dog',
breed: 'labradoodle'
},
{
type: 'cat',
breed: 'siamese'
},
{
type: 'dog',
breed: 'french bulldog'
},
{
type: 'cat',
breed: 'mud'
}
];
console.log(reGroup(animals, 'type'));
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'
},
];
console.log(reGroup(cars, 'make'));
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"));
function groupBy() {
const key = 'make';
return cars.reduce((acc, x) => ({
...acc,
[x[key]]: (!acc[x[key]]) ? [{
model: x.model,
year: x.year
}] : [...acc[x[key]], {
model: x.model,
year: x.year
}]
}), {})
}
console.log('Grouped by make key:',groupBy())
groupBy (list: any[], key: string): Map<string, Array<any>> {
let map = new Map();
list.map(val=> {
if(!map.has(val[key])){
map.set(val[key],list.filter(data => data[key] == val[key]));
}
});
return map;
});