Skip to content
Advertisement

How to duplicate an object in an array by given quantity, ES6 and above

I’m trying to convert an array of objects where i return duplicated objects if the object properties quantity is greater than 1.

const objects = [
  { id: 1, name: "Scissor", price: 2, quantity: 3 },
  { id: 2, name: "Hat", price: 6.5, quantity: 1 },
  { id: 3, name: "Socks", price: 0.5, quantity: 5 },
];


// desired return
[
  { id: 1, name: "Scissor", price: 2 }
  { id: 1, name: "Scissor", price: 2 }
  { id: 1, name: "Scissor", price: 2 }
  { id: 2, name: "Hat", price: 6.5}
  { id: 3, name: "Socks", price: 0.5 }
  { id: 3, name: "Socks", price: 0.5 }
  { id: 3, name: "Socks", price: 0.5 }
  { id: 3, name: "Socks", price: 0.5 }
  { id: 3, name: "Socks", price: 0.5 }
]

My code:

const objects = [
  { id: 1, name: "Scissor", price: 2, quantity: 3 },
  { id: 2, name: "Hat", price: 6.5, quantity: 1 },
  { id: 3, name: "Socks", price: 0.5, quantity: 5 },
];

let newObjects= [];

Object.entries(objects).forEach(([key, value]) => {

    for (let i=0; i < value.quantity; i++){
        newObjects.push({ id: value.id, name: value.name, price: value.price})
    }

});
console.log(newObjects);

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().

const objects = [
  { id: 1, name: "Scissor", price: 2, quantity: 3 },
  { id: 2, name: "Hat", price: 6.5, quantity: 1 },
  { id: 3, name: "Socks", price: 0.5, quantity: 5 },
];
let newObjects = objects.flatMap(e=>
  Array(e.quantity).fill({id: e.id, name: e.name, price: e.price})
);
console.log(newObjects);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement