Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading