Node.js:为子对象添加公共属性并追加父级汇总字段
Got it, let's tackle this problem step by step. Here's how you can achieve exactly what you need in Node.js:
Step 1: Understand the Input Structure
First, let's assume a sample products array that matches your described scenario (adjust this to match your actual data structure if needed):
const products = [ { "2024-05-01": [ { product_id: 1, total_quantity_sold: 5 }, { product_id: 2, total_quantity_sold: 3 } ] }, { "2024-05-02": [ { product_id: 1, total_quantity_sold: 2 }, { product_id: 2, total_quantity_sold: 4 } ] } ];
Step 2: Write the Processing Logic
We'll use array methods like map and reduce to handle adding common properties and calculating the total quantity:
// Define your shared public property here (customize this to your needs) const sharedProperty = { product_category: "general" }; // Process the products array const processedData = products.map(dateEntry => { // Extract the date key and its associated product list const [dateKey, productList] = Object.entries(dateEntry)[0]; // Add the public property to each product in the list const updatedProducts = productList.map(product => ({ ...product, ...sharedProperty })); // Calculate the total quantity sold for this date const totalQuantity = updatedProducts.reduce((sum, item) => { return sum + item.total_quantity_sold; }, 0); // Return the final entry with date data and total return { [dateKey]: updatedProducts, total: totalQuantity }; }); console.log(processedData);
Step 3: Verify the Output
Running the code above will produce this result, perfect for your chart data needs:
[ { "2024-05-01": [ { product_id: 1, total_quantity_sold: 5, product_category: "general" }, { product_id: 2, total_quantity_sold: 3, product_category: "general" } ], total: 8 }, { "2024-05-02": [ { product_id: 1, total_quantity_sold: 2, product_category: "general" }, { product_id: 2, total_quantity_sold: 4, product_category: "general" } ], total: 6 } ]
Key Notes
- Customize the Shared Property: Replace
product_category: "general"with whatever public attributes you need to add to child objects. - Handle Edge Cases: If your
productsarray might have entries with multiple date keys (unlikely per your description), swapObject.entries(dateEntry)[0]with a loop over all entries to process each key-value pair. - Efficiency: This approach runs in O(n*m) time where n is the number of date entries and m is the number of products per date—ideal for most charting use cases.
内容的提问来源于stack exchange,提问作者Omair Nabiel
相关产品推荐
相关产品推荐

