Skip to content
Advertisement

How to concataecance object array values of duplicates

I have an object that contains duplicate id properties and I want to reduce them to one array for each. I only figured out a way to find unique ids, but how can I concat the name attribute?

const x = [
   {id: 1, name: 'green'},
   {id: 2, name: 'red'},
   {id: 1, name: 'blue'}
]

Desired result:

[
   {id: 1, name: 'green, blue'},
   {id: 2, name: 'red'}
]

Advertisement

Answer

Simple reduce to combine and using Object.values to get the result you are after.

const x = [{
    id: 1,
    name: 'green'
  },
  {
    id: 2,
    name: 'red'
  },
  {
    id: 1,
    name: 'blue'
  }
]

const result = Object.values(x.reduce((acc, obj) => {
  if (acc[obj.id]) {
    acc[obj.id].name += ", " + obj.name;
  } else {
    acc[obj.id] = { ...obj
    };
  }
  return acc;
}, {}));

console.log(result);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement