Skip to content
Advertisement

Merging array of object in to a single array of object [closed]

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?

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement