I’m trying to convert an array of objects where i return duplicated objects if the object properties quantity is greater than 1.
JavaScript
x
20
20
1
const objects = [
2
{ id: 1, name: "Scissor", price: 2, quantity: 3 },
3
{ id: 2, name: "Hat", price: 6.5, quantity: 1 },
4
{ id: 3, name: "Socks", price: 0.5, quantity: 5 },
5
];
6
7
8
// desired return
9
[
10
{ id: 1, name: "Scissor", price: 2 }
11
{ id: 1, name: "Scissor", price: 2 }
12
{ id: 1, name: "Scissor", price: 2 }
13
{ id: 2, name: "Hat", price: 6.5}
14
{ id: 3, name: "Socks", price: 0.5 }
15
{ id: 3, name: "Socks", price: 0.5 }
16
{ id: 3, name: "Socks", price: 0.5 }
17
{ id: 3, name: "Socks", price: 0.5 }
18
{ id: 3, name: "Socks", price: 0.5 }
19
]
20
My code:
JavaScript
1
17
17
1
const objects = [
2
{ id: 1, name: "Scissor", price: 2, quantity: 3 },
3
{ id: 2, name: "Hat", price: 6.5, quantity: 1 },
4
{ id: 3, name: "Socks", price: 0.5, quantity: 5 },
5
];
6
7
let newObjects= [];
8
9
Object.entries(objects).forEach(([key, value]) => {
10
11
for (let i=0; i < value.quantity; i++){
12
newObjects.push({ id: value.id, name: value.name, price: value.price})
13
}
14
15
});
16
console.log(newObjects);
17
So my code above does work, does return what i wanted, however i feel like there is a better/smoother and more of ES6 and beyond method. Could anyone please suggest a better way?
Advertisement
Answer
You could use .fill()
and .flatMap()
.
JavaScript
1
10
10
1
const objects = [
2
{ id: 1, name: "Scissor", price: 2, quantity: 3 },
3
{ id: 2, name: "Hat", price: 6.5, quantity: 1 },
4
{ id: 3, name: "Socks", price: 0.5, quantity: 5 },
5
];
6
let newObjects = objects.flatMap(e=>
7
Array(e.quantity).fill({id: e.id, name: e.name, price: e.price})
8
);
9
console.log(newObjects);
10