我有一个对象数组作为输入。
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'}]
我需要从每个对象中删除位置并按 Material 分组。
val = [{
matnr:0001
types :[{type:'Z001',price:12.3},{type:'Z001',price:12.2}]
},
{
matnr:0002
types :[{type:'Z003',price:12.3}]
}
我试图从数组中删除一个对象并进行了分组,但似乎不起作用。你能帮忙吗
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;
});
最佳答案
您可以使用 .reduce()
与 destructuring通过创建一个对象,通过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;}
关于javascript - 从对象数组中删除对象项并在 Node js中分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58578980/