0
const array = [
{ts: 1596232800, v1: 1},
{ts: 1596232860, v1: 2},
{ts: 1596232920, v1: 3},
{ts: 1596232800, b2: 10},
{ts: 1596232860, b2: 11},
{ts: 1596232920, b2: 12},
{ts: 1596232800, c3: 20},
{ts: 1596232860, c3: 21},
{ts: 1596232920, c3: 22}
];

I want to merge objects in array with same value ts. I want this result:

const result=[
{ts: 1596232800, v1: 1, b2: 10, c3: 20},
{ts: 1596232860, v1: 2, b2: 11, c3: 21},
{ts: 1596232920, v1: 3, b2: 12, c3: 22}
]

I tried this:

const mergeArrayOfObjs = arr => Object.assign({}, ...arr);
const result = mergeArrayOfObjs(array);
console.log(result);
// Object { ts: 1596232920, v1: 3, b2: 12, c3: 22 }
Dev M
  • 1,519
  • 3
  • 29
  • 50

2 Answers2

2

I'd use a temporary object to:

const array = [{ts: 1596232800, v1: 1}, {ts: 1596232860, v1: 2}, {ts: 1596232920, v1: 3}, {ts: 1596232800, b2: 10}, {ts: 1596232860, b2: 11}, {ts: 1596232920, b2: 12}, {ts: 1596232800, c3: 20}, {ts: 1596232860, c3: 21}, {ts: 1596232920, c3: 22} ];

let res = {};
array.forEach(a => res[a.ts] = {...res[a.ts], ...a});
res = Object.values(res);

console.log(res);
[
  {
    "ts": 1596232800,
    "v1": 1,
    "b2": 10,
    "c3": 20
  },
  {
    "ts": 1596232860,
    "v1": 2,
    "b2": 11,
    "c3": 21
  },
  {
    "ts": 1596232920,
    "v1": 3,
    "b2": 12,
    "c3": 22
  }
]
0stone0
  • 34,288
  • 4
  • 39
  • 64
1

This can be solved using reduce function mdn.

const array = [
{ts: 1596232800, v1: 1},
{ts: 1596232860, v1: 2},
{ts: 1596232920, v1: 3},
{ts: 1596232800, b2: 10},
{ts: 1596232860, b2: 11},
{ts: 1596232920, b2: 12},
{ts: 1596232800, c3: 20},
{ts: 1596232860, c3: 21},
{ts: 1596232920, c3: 22}
];

const result = array.reduce((acc, value) => {
  const fIndex = acc.findIndex(v => v.ts === value.ts);
  if (fIndex >= 0) {
    acc[fIndex] = { ...acc[fIndex],
      ...value
    }
  } else {
    acc.push(value);
  }
  return acc;
}, []);

console.log(result);
Rush W.
  • 1,321
  • 2
  • 11
  • 19