0

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?

Jim41Mavs
  • 482
  • 4
  • 21
  • `Object.entries` already is ES6 and beyond. (Although it's absolutely unnecessary, since you never use the keys). – Bergi Nov 15 '20 at 18:39
  • Combine any answer from [Create an array with same element repeated multiple times](https://stackoverflow.com/q/12503146/1048572) with a `flatMap` call and you're done. – Bergi Nov 15 '20 at 18:43

2 Answers2

3

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);
Yousername
  • 1,012
  • 5
  • 15
1

You can use an array reduce along with an array fill.

The map is required only if you want to have unique references otherwise you can fill using the same object.

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 },
];

const output = objects.reduce((a, c) => {
  return a.concat(Array(c.quantity).fill({}).map(x=>({
    id: c.id,
    name: c.name,
    price: c.price
  })))
}, []);


console.log(output)
Guruparan Giritharan
  • 15,660
  • 4
  • 27
  • 50