Skip to content
Advertisement

Merge objects with same id in array in js

I guess have a dead simple problem but still didn’t find a solution I have an array which looks like this:

var originalArray = [
{
  pid: 1,
  coordinates: {x: "50", y: null, f: null}
},
{
  pid: 1,
  coordinates: {x: null, y: "22", f: null}
},
{
  pid: 1,
  coordinates: {x: null, y: null, f: "2"}
},
{
  pid: 2,
  coordinates: {x: "23", y: null, f: null}
},
{
  pid: 2,
  coordinates: {x: null, y: "62", f: null}
},
{
  pid: 2,
  coordinates: {x: null, y: null, f: "15"}
}
]

I’d like to modify it to look like this (merge by id and join elements):

var originalArray = [
{
  pid: 1,
  coordinates: {x: "50", y: "22", f: "2"}
},
{
  pid: 2,
  coordinates: {x: "23", y: "62", f: "15"}
}
]

I already had multiple tries but still didn’t find an elegant way of doing it.

Answer

You can group the array by pids and merge the non null coordinates using reduce.

const originalArray = [
  { pid: 1, coordinates: { x: "50", y: null, f: null } },
  { pid: 1, coordinates: { x: null, y: "22", f: null } },
  { pid: 1, coordinates: { x: null, y: null, f: "2" } },
  { pid: 2, coordinates: { x: "23", y: null, f: null } },
  { pid: 2, coordinates: { x: null, y: "62", f: null } },
  { pid: 2, coordinates: { x: null, y: null, f: "15" } },
];

const result = Object.values(
  originalArray.reduce((r, o) => {
    r[o.pid] ??= { pid: o.pid };
    r[o.pid].coordinates = {
      ...r[o.pid].coordinates,
      ...Object.entries(o.coordinates).reduce(
        (r, [k, v]) => (v && (r[k] = v), r),
        {}
      ),
    };
    return r;
  }, {})
);

console.log(result);

Relevant Documentations:

Advertisement