You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何展平并合并嵌套数组中的子数组?附JavaScript示例数据

Flatten and Merge Nested Transactions in JavaScript Data

Got it, let's work through this. You need to flatten those nested transactions arrays under each product and merge them into a single collection—either with their associated purchase/product details (which is usually the more practical use case) or just the raw transaction entries. Here are both approaches:

If you want each transaction entry to retain information about which purchase and product it belongs to, use nested flatMap calls combined with map to attach the context:

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

const flattenedTransactions = data.flatMap(purchase => 
  purchase.product.flatMap(product => 
    product.transactions.map(transaction => ({
      purchase_id: purchase.purchase_id,
      product_name: product.name,
      product_id: product.id,
      ...transaction // Spread the transaction's price and qty
    }))
  )
);

console.log(flattenedTransactions);

Output:

[
  { purchase_id: 1, product_name: 'A', product_id: 1, price: 5, qty: 2 },
  { purchase_id: 1, product_name: 'A', product_id: 1, price: 10, qty: 2 },
  { purchase_id: 1, product_name: 'B', product_id: 2, price: 3, qty: 4 },
  { purchase_id: 2, product_name: 'C', product_id: 3, price: 5, qty: 2 },
  { purchase_id: 2, product_name: 'D', product_id: 4, price: 3, qty: 4 }
]

Option 2: Merge Raw Transactions Only

If you don't need the purchase/product context and just want a flat array of all transaction objects, simplify the code to just nested flatMap calls:

const allRawTransactions = data.flatMap(purchase => 
  purchase.product.flatMap(product => product.transactions)
);

console.log(allRawTransactions);

Output:

[
  { price: 5, qty: 2 },
  { price: 10, qty: 2 },
  { price: 3, qty: 4 },
  { price: 5, qty: 2 },
  { price: 3, qty: 4 }
]

Quick Breakdown:

  • flatMap is ideal here because it maps over elements and flattens the resulting array by one level—no extra nested arrays cluttering the final output.
  • For the context-rich version, map lets us combine each transaction with its parent product and purchase data using object spread (...transaction) to preserve the original transaction fields.

内容的提问来源于stack exchange,提问作者Pengguna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:23:04