Considering the following JSON object example as input, how would you use Javascript to duplicate each object based on the number of times found in the "Count" key/value pair?
Example Input:
[
{ "name":"David", "Count":2 },
{ "name":"John", "Count":3 },
]
Expected Output:
[
{ "name": "David" },
{ "name": "David" },
{ "name": "John" },
{ "name": "John" },
{ "name": "John" },
]
You can iterate on the Count property and push into another array.
var data = [{
"name": "David",
"Count": 2
},
{
"name": "John",
"Count": 3
}
];
const output = [];
data.forEach(({ name, Count}) => {
for(let i = 0; i < Count; i++) {
output.push({ name });
}
});
console.log(output);
You can do it easily with reduce() function:
let data = [
{ "name": "David", "Count": 2 },
{ "name": "John", "Count": 3 },
]
let new_data = data.reduce((sum, current) => {
for (let index = 0; index < current.Count; index++) {
sum.push({ name: current.name })
};
return sum
}, []);
console.log(new_data)
I would do something like that
const output = input.reduce((acc, cur) => [
...acc,
...Array.from({length: cur.Count}).map(() => ({ name: cur.name })
], [])