Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
How can you use Javascript to duplicate a JSON object based on the value of a key in the object?

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

I would do something like that

const output = input.reduce((acc, cur) => [
    ...acc,
    ...Array.from({length: cur.Count}).map(() => ({ name: cur.name })
], [])
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!