如何从每个子数组中展平和合并嵌套数组

时间:2018-04-24 08:19:47

标签: javascript arrays object

所以我有这些数据:

target_x

我希望从每个let data = [ { "purchase_id": 1, "product": [ { "name": "A", "id": 1, "transactions": [ { "price": 5, "qty": 2 }, { "price": 10, "qty": 2 } ] }, { "name": "B", "id": 2, "transactions": [ { "price": 3, "qty": 4 } ] } ] }, { "purchase_id": 2, "product": [ { "name": "C", "id": 3, "transactions": [ { "price": 5, "qty": 2 } ] }, { "name": "D", "id": 4, "transactions": [ { "price": 3, "qty": 4 } ] } ] } ] 数据中展平数组:

data.product.transactions

预期输出为:

"transactions": [
    {
       "price",
       "qty"
    }
 ]

我试过使用对象分配,减少但我的代码不起作用。谢谢

2 个答案:

答案 0 :(得分:1)

使用嵌套Array.map()创建对象,使用spread导入Array.concat()以展平每个级别的子数组:



const data = [{"purchase_id":1,"product":[{"name":"A","id":1,"transactions":[{"price":5,"qty":2},{"price":10,"qty":2}]},{"name":"B","id":2,"transactions":[{"price":3,"qty":4}]}]},{"purchase_id":2,"product":[{"name":"C","id":3,"transactions":[{"price":5,"qty":2}]},{"name":"D","id":4,"transactions":[{"price":3,"qty":4}]}]}];

const result = [].concat(...data.map(({ purchase_id, product }) => 
  [].concat(...product.map(({ name, id, transactions }) => 
    transactions.map((o) => ({
      purchase_id,
      name,
      id,
      ...o
    })
)))));

console.log(result);




如果要避免临时子数组和讨人喜欢,请使用嵌套的Array.forEach()调用,并将创建的对象推送到预定义的数组:



const data = [{"purchase_id":1,"product":[{"name":"A","id":1,"transactions":[{"price":5,"qty":2},{"price":10,"qty":2}]},{"name":"B","id":2,"transactions":[{"price":3,"qty":4}]}]},{"purchase_id":2,"product":[{"name":"C","id":3,"transactions":[{"price":5,"qty":2}]},{"name":"D","id":4,"transactions":[{"price":3,"qty":4}]}]}];

const result = [];

data.forEach(({ purchase_id, product }) => 
  product.forEach(({ name, id, transactions }) => 
    transactions.forEach((o) => result.push({
      purchase_id,
      name,
      id,
      ...o
    })
)));

console.log(result);




答案 1 :(得分:1)

var arr = [];
data.forEach(x => {
  x.product.forEach(y => {
    y.transactions.forEach(z => {
      z["name"] = y.name;
      z["id"] = y.id;
      z["purchase_id"] = x.purchase_id;
      arr.push(z);
    });
  })
});
console.log(arr);