javascript - 从对象数组中删除对象项并在 Node js中分组

标签 javascript 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'}]

我需要从每个对象中删除位置并按 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/

相关文章:

javascript - Twitter Bootstrap Popovers - 如何让它们留下来?

javascript - 将定义添加到 Typescript 中的现有模块

javascript - JS GetElementByClassName[0] 返回未定义

javascript - Node.js:如何在检索数据( block )时关闭响应/请求

node.js - 使用毫秒设置日期

java - 了解Android的webview addjavascriptinterface

javascript - 经典 ASP 到 ASP.NET 4.0 的同源策略

node.js - nodejs sequelize/cli 如何与 Node 配置一起使用

node.js - 无法在 Node.js 中销毁 Twitter 流

node.js - 如何使用Github API推送代码?