Home > database >  Javascript - Unify between objects values within an array
Javascript - Unify between objects values within an array

Time:12-29

How can I unify between objects values within an array that have same key using javascript?

for example if i have this array:

0: {key: 'abc1', value: 'product1'}
1: {key: 'abc2', value: "product2"}
2: {key: 'abc2', value: 'product3'}

and i want result array to be like that:

  0: {key: 'abc1', value: 'product1'}
  1: {key: 'abc2', value: "product2, product3"}

CodePudding user response:

Here is a pretty manual way of doing it, I'm sure there is a more elegant solution, but can't think of one off the top of my head.

val = [
  {key: 'abc1', value: 'product1'},
  {key: 'abc2', value: 'product2'},
  {key: 'abc2', value: 'product3'}
];

newVal = [];

val.forEach((objToAdd)=>{
    let match = newVal.find((obj)=>obj.key===objToAdd.key);
    if(match){
        match.value=`${match.value}, ${objToAdd.value}`;
    } else {
        newVal.push(objToAdd);
    }
});

console.log(newVal);

  • Related