如何在嵌套数组中移动元素 [英] How to move element in nested array

查看:80
本文介绍了如何在嵌套数组中移动元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在嵌套数组中移动元素.所以,这是我的数据:

i wanted to move element in nested array. so, here this my data:

let products = [
    {     
      "product_name": "A",
      "_id": "5ace995c14a759325776aab1",
      "transactions": [
        {
          "_id": "5ad3a274ac827c165a510f99",
          "qty": 100,
          "price": 2000
        },
        {
          "_id": "5ad3a274ac827c165a510f99",
          "qty": 80,
          "price": 1500
        },
      ]
    },
    {
      "product_name": "B",
      "_id": "5ace995914a759325776aab0",
      "transactions": [
        {
          "_id": "5ad3a274ac827c165a510f9b",
          "qty": 80,
          "price": 1500
        }
      ],
    }
  ]

我期望的输出:

[
  {
    "_id": "5ad3a274ac827c165a510f99",
    "qty": 100,
    "price": 2000,
    "product_name": "A",
  },
  {
    "_id": "5ad3a274ac827c165a510f99",
    "qty": 80,
    "price": 1500,
    "product_name": "A",
  },
  {
    "_id": "5ad3a274ac827c165a510f9b",
    "qty": 80,
    "price": 1500,
    "product_name": "B",
  }
]

然后,我的求解代码:

function move() {
  var result = []
  for (product of products) {
    for (transaction of product.transactions) {
      transaction.product_name = product.product_name
      result.push(transaction)
    }
  }
  return result
}
product = move()

是否存在任何有效的创建输出的方法,例如使用数组映射或其他任何方法?谢谢.

Is there any effective way to create the output, maybe with array map or anything else? Thank you.

推荐答案

您可以使用也使用:

简写属性用于将变量作为属性并以名称作为键.

short hand properties for taking a variable as property with the name as key.

var products = [{ product_name: "A", _id: "5ace995c14a759325776aab1", transactions: [{ _id: "5ad3a274ac827c165a510f99", qty: 100, price: 2000 }, { _id: "5ad3a274ac827c165a510f99", qty: 80, price: 1500 }] }, { product_name: "B", _id: "5ace995914a759325776aab0", transactions: [{ _id: "5ad3a274ac827c165a510f9b", qty: 80, price: 1500 }] }],
    result = products.reduce((r, { transactions, product_name }) =>
        r.concat(transactions.map(t => Object.assign({}, t, { product_name }))),
        []
    );
  
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

这篇关于如何在嵌套数组中移动元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆