Home > Blockchain >  How to Merge duplicate fields and their values in array of objects
How to Merge duplicate fields and their values in array of objects

Time:09-22

Seeking for help in a JavaScript problem. I am new to Nodejs, JavaScript. I am trying to merge duplicate values in the array if exists.

In below example - I have multiple asset_id which is repeated so I need to keep one and merge their values. I tried to do that but not getting the proper solution and output for the same.

const transaction = [{
    total_duration: 5,
    asset_id: 'ABC',
}, {
    total_duration: 15,
    asset_id: 'HGF',
}, {
    total_duration: 15,
    asset_id: 'XYZ',
}, {
    total_duration: 20,
    asset_id: 'XYZ',
}, {
    total_duration: 25,
    asset_id: 'DEF',
}, {
    total_duration: 20,
    asset_id: 'HGF',
}, {
    total_duration: 20,
    asset_id: 'HGF',
},
{
    total_duration: 10,
    asset_id: 'ABC',
}];

let newArr = [];
transaction.forEach(function (obj, ind, arr) {
    if (ind === arr.length - 1 || obj.asset_id !== arr[ind   1].asset_id) {
        newArr.push(obj);
    } else {
        arr[ind   1].total_duration  = obj.total_duration;
    }
});

console.log(newArr)

CodePudding user response:

I call this "group array of objects by property using reduce then getting values of it"

const transaction = [{total_duration:5,asset_id:"ABC"},{total_duration:15,asset_id:"HGF"},{total_duration:15,asset_id:"XYZ"},{total_duration:20,asset_id:"XYZ"},{total_duration:25,asset_id:"DEF"},{total_duration:20,asset_id:"HGF"},{total_duration:20,asset_id:"HGF"},{total_duration:10,asset_id:"ABC"}];

console.log(Object.values(transaction.reduce(function(agg, item) {
  agg[item.asset_id] = agg[item.asset_id] || {
    asset_id: item.asset_id,
    total_duration: 0

  }
  agg[item.asset_id].total_duration  = item.total_duration
  return agg;
}, {})))
.as-console-wrapper {max-height: 100% !important}

CodePudding user response:

const transaction = [{
    total_duration: 5,
    asset_id: 'ABC',
}, {
    total_duration: 15,
    asset_id: 'HGF',
}, {
    total_duration: 15,
    asset_id: 'XYZ',
}, {
    total_duration: 20,
    asset_id: 'XYZ',
}, {
    total_duration: 25,
    asset_id: 'DEF',
}, {
    total_duration: 20,
    asset_id: 'HGF',
}, {
    total_duration: 20,
    asset_id: 'HGF',
},
{
    total_duration: 10,
    asset_id: 'ABC',
}];

const result = transaction.reduce((a, b) => {
      const id = b["asset_id"]
      const value = b["total_duration"]
      if (a[id]) {
            a[id] = a[id]   value
      return a 
      } else {
             a[id] = value 
                 return a
      }
}, {})
console.log(result)

  • Related