Imagine having an array structured like this:
[
{
id: 1,
name: "Foo",
quantity: 2
},
{
id: 2,
name: "Bar",
quantity: 3
},
]
The goal is to duplicate or expand the array elements based on the quantity
value. The expected output should look like this:
[
{
id: 1,
name: "Foo"
},
{
id: 1,
name: "Foo"
},
{
id: 2,
name: "Bar"
},
{
id: 2,
name: "Bar"
},
{
id: 2,
name: "Bar"
}
]
Is it possible to achieve this outcome without resorting to a loop (for, forEach, etc..)? Can the native methods of the Array
object be utilized?
Update:
In case anyone finds it useful, here is a loop-based solution.
const arrayOfObjects = [
{
id: 1,
name: "Foo",
quantity: 2
},
{
id: 2,
name: "Bar",
quantity: 3
},
];
let result = [];
arrayOfObjects.forEach(element => {
for (let i = 0; i < element.quantity; i++) {
const {
quantity,
...newElement
} = element;
result.push(newElement);
}
});