popeating
popeating

Reputation: 454

Merging/grouping objects in ReactJS

I have the following arrays:

  [{id:0,name:'Weight',option:'250'},{id:0,name:'Roast',option:'Medium'}]
  [{id:0,name:'Weight',option:'250'},{id:0,name:'Roast',option:'Light'}]

I need to merge them in something like:

[{id:0,name:'Weight',options:['250']},{id:0,name:'Roast',options:['Medium','Light']}]

I tried to nest some loops also tried with merge, push and spread operators but I can't solve it

result.forEach((att) => {
  let newoptions = [];
  console.log('att', att.attributes);
   att.attributes.forEach((id, idx) => {
     console.log('id', id);
     newoptions = [...newoptions, { option: id.option }];
     newAttr[idx] = { name: id.name, options: newoptions };
   });

});

Upvotes: 1

Views: 230

Answers (2)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Use flat and forEach. Build an object with keys as name and aggregate the values.

const process = (...data) => {
  const res = {};

  data.flat().forEach(({ name, option, id }) => {
    res[name] ??= { name, id, options: [] };
    !res[name].options.includes(option) && res[name].options.push(option);
  });
  return Object.values(res);
};

const arr1 = [
  { id: 0, name: "Weight", option: "250" },
  { id: 0, name: "Roast", option: "Medium" },
];
const arr2 = [
  { id: 0, name: "Weight", option: "250" },
  { id: 0, name: "Roast", option: "Light" },
];

console.log(process(arr1, arr2));

Upvotes: 1

lissettdm
lissettdm

Reputation: 13078

I recommend you to concat both arrays and then iterate over it. Then reduce the items with Array.prototype.reduce():

const data1 = [{ id: 0, name: "Weight", option: "250" },{ id: 0, name: "Roast", option: "Medium" }];

const data2 = [{ id: 0, name: "Weight", option: "250" },{ id: 0, name: "Roast", option: "Light" }];

const array = [...data1, ...data2]; // concat
const result = array.reduce((o, c) => {
  const exist = o.find(item => item.id === c.id && item.name === c.name);
  if (!exist) {
    const options = array
      .filter(item => item.id === c.id && item.name === c.name)
      .map(item => item.option);
    o.push({ id: c.id, name: c.name, options: Array.from(new Set(options)) });
  }
  return o;
}, []);

console.log(result);

Upvotes: 1

Related Questions