如何基于2个键合并数组对象?

时间:2019-02-12 07:50:45

标签: javascript arrays

这是我的代码

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中实现此功能。

1 个答案:

答案 0 :(得分:3)

您可以使用reduceObject.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作为键。在Status处分割"Product ",然后使用destructuringsuffix变量的结果数组中取出第二项。 (或者您可以简单地使用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"
  }
}

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