2

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

2 Answers 2

4

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.