Jayanta Baishya
Jayanta Baishya

Reputation: 97

Check and convert duplicate object with condition in javascript array

I have an array, e.g.

[ { key: 'NAME', value: 'JAY'},
     { key: 'AGE', value: '65'},
     { key: 'YEAR', value: '2017'},
     { key: 'PLACE', value: 'Delhi'},
     { key: 'PLACE', value: 'Mumbai'},
     { key: 'YEAR', value: '2018'}
]

want to convert it to the below List based on the duplicate key

[ { key: 'NAME', value: ['JAY']},
     { key: 'AGE', value: ['65']},
     { key: 'YEAR', value: ['2017','2018']},
     { key: 'PLACE', value: ['Delhi','Mumbai']}
]

Please help ..

Upvotes: 0

Views: 224

Answers (1)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48367

You can use reduce method by passing a callback provided function as argument.

var array = [ { key: 'NAME', value: 'JAY'},
     { key: 'AGE', value: '65'},
     { key: 'YEAR', value: '2017'},
     { key: 'PLACE', value: 'Delhi'},
     { key: 'PLACE', value: 'Mumbai'},
     { key: 'YEAR', value: '2018'}
]

let result = array.reduce(function(arr, item){
  let foundElem = arr.find(elem => elem.key === item.key);
  if(!foundElem)
     arr.push({key : item.key, value : [item.value]});  
  else
    foundElem.value.push(item.value);
  return arr;
}, []);
console.log(result);

Upvotes: 1

Related Questions