Skip to content
Advertisement

How to merge the multiple object if the key value equal

I have an array of objects. In each object, I have the ‘date’ key. if the ‘date’ value is matched with another object, I need to add the ‘amount’ property and make it a new object.

var obj = [
  {
    'date':'2017-02-08T00:00:00.000Z',
    'amount': 20000
  },{
    'date':'2017-02-11T00:00:00.000Z',
    'amount': 65989
  },{
    'date':'2017-02-08T00:00:00.000Z',
    'amount': 256
  },{
    'date':'2017-02-08T00:00:00.000Z',
    'amount': 269
  },{
    'date':'2017-02-11T00:00:00.000Z',
    'amount': 900
  },{
    'date':'2017-02-11T00:00:00.000Z',
    'amount': 6982.99
  },{
    'date':'2017-02-18T00:00:00.000Z',
    'amount': 15248.09
  },
];

Object.keys(obj).map(data1 =>{
  Object.keys(obj).map(data2 =>{
    if(obj[data]['date'] == obj[data2]['date']){
      // i dont know what to do here. 
    }
  }); 
})

My expected output should be:

[
  {
    'date':'2017-02-08T00:00:00.000Z',
    'amount': 20525
  },{
    'date':'2017-02-11T00:00:00.000Z',
    'amount': 73,871.99
  },{
    'date':'2017-02-18T00:00:00.000Z',
    'amount': 15248.09
  },
]

Kindly help me to solve it.

Advertisement

Answer

You can use Array.reduce to calculate a sum per date value. Something like:

var obj = [
  {
    'date':'2017-02-08T00:00:00.000Z',
    'amount': 20000
  },{
    'date':'2017-02-11T00:00:00.000Z',
    'amount': 65989
  },{
    'date':'2017-02-08T00:00:00.000Z',
    'amount': 256
  },{
    'date':'2017-02-08T00:00:00.000Z',
    'amount': 269
  },{
    'date':'2017-02-11T00:00:00.000Z',
    'amount': 900
  },{
    'date':'2017-02-11T00:00:00.000Z',
    'amount': 6982.99
  },{
    'date':'2017-02-18T00:00:00.000Z',
    'amount': 15248.09
  },
];

// reduce to object with date keys, amount values
const totals = obj.reduce( (acc, val) => (
  { ...acc, [val.date]: (acc[val.date] || 0) + val.amount } ), {} );

// map back to array
const totalsMapped = Object.entries(totals).map( ([key, value]) => ( 
  {date: key, amount: value} ) );

Logger()( 
  `Reduced:`,
  JSON.stringify(totals, null, 2), 
  `Mapped:`,
  JSON.stringify(totalsMapped, null, 2) 
);

function Logger() {
  const pre = document.querySelector('pre')
  return (...lines) => lines.forEach(line => pre.textContent += `${line}n`)
}
<pre></pre>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement