[英]Given an array of objects how can I merge Objects within the array based of the keys?
[英]How to merge array objects based on 2 keys?
这是我的代码
var array = [{ OrderId: "L01", Location: "London" Qty: "6.00", Status: "Product A }, { OrderId: "L01", Location: "London" Qty: "2.00" Status: "Product B" }, { OrderId: "L01", Location: "London" Qty: "3.00" Status: "Product C" }, { OrderId: "P01", Location: "Paris" Qty: "7.00" Status: "Product A" }, { OrderId: "P01", Location: "Paris" Qty: "4.00" Status: "Product B" }, { OrderId: "P01", Location: "Paris" Qty: "9.00" Status: "Product C" } ];
我想将此数组转换为
var arrayModified = [{
OrderId: "L01",
Location: "London"
QtyA: "6.00",
QtyB: "2.00,
QtyC: "3.00
},
{
OrderId: "P01",
Location: "London"
Qty: A "7.00",
QtyB: "4.00",
QtyC: "9.00"
}
];
基本上,我想检查称为状态的变量,并根据此变量创建新字段QtyA,QtyB,QtyC。 OrderId和Plant是常见且唯一的字段。
没有Jquery和Lodash的情况下,如何在普通JS中实现此功能。
您可以使用reduce
和Object.values
进行此操作
var array = [{OrderId:"L01",Location:"London",Qty:"6.00",Status:"Product A"},{OrderId:"L01",Location:"London",Qty:"2.00",Status:"Product B"},{OrderId:"L01",Location:"London",Qty:"3.00",Status:"Product C"},{OrderId:"P01",Location:"Paris",Qty:"7.00",Status:"Product A"},{OrderId:"P01",Location:"Paris",Qty:"4.00",Status:"Product B"},{OrderId:"P01",Location:"Paris",Qty:"9.00",Status:"Product C"}]; const merged = array.reduce((r,{OrderId, Location, Status, Qty}) => { const [p,suffix] = Status.split("Product ") r[OrderId] = r[OrderId] || {OrderId, Location}; r[OrderId]["Qty"+suffix] = Qty; return r; },{}) const output = Object.values(merged) console.log(output)
目标是创建一个以每个唯一的OrderId
为键的accumulator
对象。 在"Product "
处拆分Status
,并使用解构从suffix
变量的结果数组中获取第二项。 (或者,您可以简单地使用replace: var suffix = Status.replace("Product ", "")
))。 然后使用Object.values
将此对象的值获取到数组。
merged
/累加器看起来像这样:
{
"L01": {
"OrderId": "L01",
"Location": "London",
"QtyA": "6.00",
"QtyB": "2.00",
"QtyC": "3.00"
},
"P01": {
"OrderId": "P01",
"Location": "Paris",
"QtyA": "7.00",
"QtyB": "4.00",
"QtyC": "9.00"
}
}
(请确保您输入的数据有效。缺少逗号和引号。我不确定代码或输入是否存在问题。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.