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

99
Views
Merging array of object in to a single array of object

I am trying to merge all the items object from a JSON file into a single item object. The JSON file structure looks like this;

[
  {"items":["product1","product2","product3"]},
  {"items":["product4","product5","product6"]},
]

What I want to achieve is to merge all the items into a single items object such as;

[
  {"items":["product1","product2","product3,"product4","product5","product6"]},
]

I have been trying concat, or spreading but couldn't make either work. How can I achieve this or what is the best method to use in this case?

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

0

You want reduce, a function whose job it is to "reduce" a list of values to a single value. In JavaScript, reduce is a method on every array. The first parameter to reduce is a function taking the current tally, then the current item, and returns the next tally. The second argument to reduce is the initial value of the tally, in our case an 'items' object with and empty array.

const LIST = [
  {"items":["product1","product2","product3"]},
  {"items":["product4","product5","product6"]},
]

const { items } = LIST.reduce((acc, element) => ({
  items: [...acc.items, ...element.items]
}), { items: [] })

console.log(items)

about 4 years ago · Juan Pablo Isaza Report

0

Use Array.reduce() and the spread operator to push the items into a single object and array:

const arr = [
  {"items":["product1","product2","product3"]},
  {"items":["product4","product5","product6"]},
]

const res = arr.reduce((acc, cur) => {
  acc[0].items.push(...cur.items);
  return acc;
}, [{'items': []}]);

console.log(res);

about 4 years ago · Juan Pablo Isaza Report

0

There doesn't much point in an array with only one object. Why not create an array and push/spread each object's items value into it with a simple loop. A lot more readable than reduce.

const data = [
  { items: ['product1', 'product2', 'product3'] },
  { items: ['product4', 'product5', 'product6'] }
];

const items = [];

for (const obj of data) {
  items.push(...obj.items);
}

console.log(items);

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!