Node.js中根据数量遍历数组并转换数组结构的实现方案咨询
Hey there! Let's walk through how to convert your input data structure into the desired format in Node.js. The key goal is to take each item with its upc and quantity, then create multiple barcode objects (one for each quantity unit) and collect them into the products array.
Approach 1: Functional Style with Array.reduce and Array.from
This method uses JavaScript's array methods to keep the code concise and declarative. We'll use reduce to iterate over the items and build our final products array, and Array.from to generate the repeated barcode objects safely (avoiding shared object references).
const input = { items: [{ upc: 'a', quantity: 2 }, { upc: 'b', quantity: 3 }] }; const output = { products: input.items.reduce((accumulator, currentItem) => { // Generate an array of 'quantity' unique barcode objects const expandedItems = Array.from( { length: currentItem.quantity }, () => ({ barcode: currentItem.upc }) ); // Add these to our accumulator array return accumulator.concat(expandedItems); }, []) // Start with an empty accumulator array }; console.log(output); // Output: { products: [{ barcode: 'a' }, { barcode: 'a' }, { barcode: 'b' }, { barcode: 'b' }, { barcode: 'b' }] }
Why Array.from instead of Array.fill?
Array.fill({ barcode: currentItem.upc }) would create an array where all elements reference the same object, which could lead to unexpected bugs if you later modify any of these objects. Array.from creates a new object for each element, ensuring they're independent.
Approach 2: Imperative Style with Nested Loops
If you prefer a more straightforward, easy-to-follow approach (great for beginners or when you need more control), nested loops work perfectly here:
const input = { items: [{ upc: 'a', quantity: 2 }, { upc: 'b', quantity: 3 }] }; const products = []; // Loop through each item in the input for (const item of input.items) { // Loop 'quantity' times, pushing a new barcode object each time for (let i = 0; i < item.quantity; i++) { products.push({ barcode: item.upc }); } } const output = { products }; console.log(output); // Same desired output as above
Both approaches will give you exactly the format you need. The functional style is cleaner for simple cases, while the loop approach is more explicit and easier to debug if you need to add extra logic during the expansion.
内容的提问来源于stack exchange,提问作者Sindhu1990

