Home > OS >  Merging array of object in to a single array of object
Merging array of object in to a single array of object

Time:05-11

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?

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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

  • Related