gpt4 book ai didi

javascript - 如何根据2个键合并数组对象?

转载 作者:行者123 更新时间:2023-11-28 17:10:11 25 4
gpt4 key购买 nike

这是我的代码

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"
}
];

基本上我想检查名为 status 的变量,并基于此我必须创建新字段 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)

目标是创建一个 accumulator 对象,并以每个唯一的 OrderId 作为键。在 "Product " 处拆分 Status 并使用 destructuringsuffix 变量中的结果数组中获取第二项。 (或者您可以简单地使用替换:var suffix = Status.replace("Product ", ""))。然后使用Object.values将该对象的值获取到数组中。

合并/accumulator 如下所示:

{
"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"
}
}

(请确保您有有效的输入数据。缺少逗号和引号。我不确定我的代码或输入是否有问题。)

关于javascript - 如何根据2个键合并数组对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54645169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com