Skip to content
Advertisement

How can I merge two objects inside an array, and compute the total of its element?

What’s the best way to merge objects and total its element? I can’t figure out how to merge it at the same time total its chats count

here’s my array:

  [
   [
    {
      id: 'call_000001',
      date: 2019-04-01T00:00:00.000Z,
      chats: 121,
      missedChats: 0
    },
    {
      id: 'call_000001',
      date: 2019-04-02T00:00:00.000Z,
      chats: 92,
      missedChats: 1
    }
  ],
  [
    {
      id: 'call_000002',
      date: 2019-04-01T00:00:00.000Z,
      chats: 13,
      missedChats: 0
    },
    {
      id: 'call_000002',
      date: 2019-04-02T00:00:00.000Z,
      chats: 12,
      missedChats: 3
    }
  ],
  ]

here’s what I want to achieve

[
 {
  id: 'call_000001',
  chats: 213,
  missedChats: 1,
 },
 {
  id: 'call_000002',
  chats: 25,
  missedChats: 3,
 },
]

what’s the best way to achieve that? without using underscore or lodash

Advertisement

Answer

Try this :

data = [
  [{
      id: 'call_000001',
      date: '2019-04-01T00:00:00.000Z',
      chats: 121,
      missedChats: 0
    },
    {
      id: 'call_000001',
      date: '2019-04-02T00:00:00.000Z',
      chats: 92,
      missedChats: 1
    }
  ],
  [{
      id: 'call_000002',
      date: '2019-04-01T00:00:00.000Z',
      chats: 13,
      missedChats: 0
    },
    {
      id: 'call_000002',
      date: '2019-04-02T00:00:00.000Z',
      chats: 12,
      missedChats: 3
    }
  ]
]


var mergedData = data.map(dataEl => dataEl.reduce((ac, el) => {
  return {
    id: ac.id,
    chats: ac.chats + el.chats,
    missedChats: ac.missedChats + el.missedChats
  }
}));


console.log(mergedData);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement