[英]Remove object items from array of objects and group in node js
我有一个对象数组作为输入。
var val = [{matnr :'0001',type:'Z0001',price:12.3,location:'Afr'},{matnr :'0001',type:'Z0002',price:12.2,location:'US'},
,{matnr :'0002',type:'Z0003',price:11.2,location:'EU'}]
我需要从每个 object 中删除位置并按材料分组。
val = [{
matnr:0001
types :[{type:'Z001',price:12.3},{type:'Z001',price:12.2}]
},
{
matnr:0002
types :[{type:'Z003',price:12.3}]
}
我试图从一个数组中删除一个 object 并做了一个 group by 但似乎没有用。 能否请你帮忙
val.forEach((values)=>
Object.keys(values).forEach(function (item) {
if (item !='matnr'||item !='type' || item != price){
delete values[item];
};
})
var grouped = _.groupBy(val, function(val) {
return val.matnr;
});
只需使用高阶函数,您就可以在不使用 loadash 的情况下做到这一点
const cleaned = removeFromList(list).key('location')
const grouped = group(list).by('matnr')
function removeFromList(arr) {
return {
key: key => arr.map(item => {
if (!item[key]) return item
delete item[key]
return item
})
}
}
function group(arr) {
return {
by: groupKey => {
const groupsObj = arr.reduce((groups, item) => {
const groupKeyValue = item[groupKey]
if(!groupKeyValue) return groups
if (!groups[groupKeyValue]){
groups[groupKeyValue] = [item]
return groups
}
groups[groupKeyValue] = [...groups[groupKeyValue], item]
return groups
}, {});
return groupsObj
}
}
}
注意我们更喜欢 object 结构以获得性能和作为开发人员易于访问,因此按 function 分组,我们返回分组的 object,材料值作为键,匹配值作为它们的值。 喜欢:
{
0001 : [{type:'Z001',price:12.3},{type:'Z001',price:12.2}]
0002 : [{type:'Z003',price:12.3}]
}
repl.it上提供的示例
您可以使用.reduce()
进行解构,通过创建 object 来通过matnr
删除location
属性和组属性,其中每个键是matnr
,每个值都是给定matnr
的属性的累积,如下所示:
const arr = [{matnr:"0001",type:"Z0001",price:12.3,location:"Afr"},{matnr:"0001",type:"Z0002",price:12.2,location:"US"},{matnr:"0002",type:"Z0003",price:11.2,location:"EU"}]; const res = Object.values(arr.reduce((acc, {matnr, type, price}) => { const {types = []} = acc[matnr] || {}; acc[matnr] = {matnr, types: [...types, {type, price}]}; return acc; }, Object.create(null))); console.log(res);
.as-console-wrapper {max-height: 100%;important;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.