heisenberg7584
heisenberg7584

Reputation: 740

Duplicate objects in array of objects by count value

I am looking for a way to modify array of objects like this:

[
  {
    id: 1,
    name: 'xyz',
    count: 3,
  },
  {
    id: 2,
    name: 'aaa',
    count: 2,
  },
  {
    id: 6,
    name: 'bbb',
    count: 1,
  },
]

Now I want to map it shomehow to receive new array of objects without count properties but with duplicated objects by its count value. We will have:

[
  {
    id: 1,
    name: 'xyz',
  },
  {
    id: 1,
    name: 'xyz',
  },
  {
    id: 1,
    name: 'xyz',
  },
  {
    id: 2,
    name: 'aaa',
  },
  {
    id: 2,
    name: 'aaa',
  },
  {
    id: 6,
    name: 'bbb',
  },
]

I tried to do it with map and reduce but it didn't work out as expected...

Upvotes: 2

Views: 49

Answers (2)

Kerlos Bekhit
Kerlos Bekhit

Reputation: 128

Nina Scholz solution works fine, if you want something easier to read:

var data = [{
    id: 1,
    name: 'xyz',
    count: 3,
  },
  {
    id: 2,
    name: 'aaa',
    count: 2,
  },
  {
    id: 6,
    name: 'bbb',
    count: 1,
  },
];

var output = [];
for (var i = 0; i < data.length; i++) {
  var element = data[i];
  for (var j = 0; j < element.count; j++) {
    output.push({
      id: element.id,
      name: element.name
    });
  }
}
console.log(output);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386550

You could use a nested mapping with an outer Array#flatMap.

var data = [{ id: 1, name: 'xyz', count: 3 }, { id: 2, name: 'aaa', count: 2 }, { id: 6, name: 'bbb', count: 1 }],
    result = data.flatMap(({ count, ...o }) =>
        Array.from({ length: count }, _ => ({ ... o })));

console.log(result);

Upvotes: 4

Related Questions