1
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 }

2 Answers 2

3

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
  }
]
Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.