Home > Software design >  combine array of object if atleast one property is common
combine array of object if atleast one property is common

Time:01-21

//this one is actual array

 const data = [
        {
          name: 'shanu',
          label: 'ak',
          value: 1,
        },
        {
          name: 'shanu',
          label: 'pk',
          value: 2,
        },
        {
          name: 'bhanu',
          label: 'tk',
          value: 3,
        },
      ];
>

//and this  is the array that I want
let outPut =
[
{
name:'shanu',
label:['ak','pk'],
value:[1,2]
},
{
name:'bhanu',
label:['tk'],
value:[3]
}
]

CodePudding user response:

You can use Array.prototype.reduce() like this:

const data = [
  {
    name: 'shanu',
    label: 'ak',
    value: 1,
  },
  {
    name: 'shanu',
    label: 'pk',
    value: 2,
  },
  {
    name: 'bhanu',
    label: 'tk',
    value: 3,
  },
];

const output = data.reduce((prev, curr) => {
  const tmp = prev.find((e) => e.name === curr.name)
  if (tmp) {
    tmp.label.push(curr.label)
    tmp.value.push(curr.value)
  } else {
    prev.push({
      name: curr.name,
      label: [curr.label],
      value: [curr.value],
    })
  }
  return prev
}, [])

console.log(output)

  •  Tags:  
  • Related