如何展平并合并嵌套数组中的子数组?附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:
Option 1: Keep Purchase & Product Context (Recommended)
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:
flatMapis 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,
maplets us combine each transaction with its parent product and purchase data using object spread (...transaction) to preserve the original transaction fields.
内容的提问来源于stack exchange,提问作者Pengguna
相关产品推荐
相关产品推荐

