Skip to content Skip to sidebar Skip to footer

How To Merge An Array Of Objects By Key?

I have this object: [{ 'NOMOR_CB': 'CB/20-0718', 'ITEM': 'ABC' }, { 'NOMOR_CB': 'CB/20-0719', 'ITEM': 'A1' }, { 'NOMOR_CB': 'CB/20-0719', 'ITEM': 'A2' }] I'd to merge

Solution 1:

You can use .reduce() to summarise your array into an object. Use Object.entries to convert the object into an array. You can map to form the desired object format.

let arr = [{"NOMOR_CB":"CB/20-0718","ITEM":"ABC"},{"NOMOR_CB":"CB/20-0719","ITEM":"A1"},{"NOMOR_CB":"CB/20-0719","ITEM":"A2"}];

let result = Object.entries(arr.reduce((c, {NOMOR_CB,ITEM}) => {
  c[NOMOR_CB] = c[NOMOR_CB] || [];
  c[NOMOR_CB].push(ITEM);
  return c;
}, {})).map(([i, a]) =>Object.assign({}, {NOMOR_CB: i,ITEM: a.join(', ')}));

let str = JSON.stringify(result); //Optional. Based on your code, you are trying to make a string.console.log(str);

And dont concatenate strings to form a json. You can use JSON.stringify(result); to convert js object to string.

Doc: .reduce(), .map()

Post a Comment for "How To Merge An Array Of Objects By Key?"