I guess have a dead simple problem but still didn’t find a solution I have an array which looks like this:
JavaScript
x
27
27
1
var originalArray = [
2
{
3
pid: 1,
4
coordinates: {x: "50", y: null, f: null}
5
},
6
{
7
pid: 1,
8
coordinates: {x: null, y: "22", f: null}
9
},
10
{
11
pid: 1,
12
coordinates: {x: null, y: null, f: "2"}
13
},
14
{
15
pid: 2,
16
coordinates: {x: "23", y: null, f: null}
17
},
18
{
19
pid: 2,
20
coordinates: {x: null, y: "62", f: null}
21
},
22
{
23
pid: 2,
24
coordinates: {x: null, y: null, f: "15"}
25
}
26
]
27
I’d like to modify it to look like this (merge by id and join elements):
JavaScript
1
11
11
1
var originalArray = [
2
{
3
pid: 1,
4
coordinates: {x: "50", y: "22", f: "2"}
5
},
6
{
7
pid: 2,
8
coordinates: {x: "23", y: "62", f: "15"}
9
}
10
]
11
I already had multiple tries but still didn’t find an elegant way of doing it.
Advertisement
Answer
You can group the array by pid
s and merge the non null coordinates
using reduce
.
JavaScript
1
24
24
1
const originalArray = [
2
{ pid: 1, coordinates: { x: "50", y: null, f: null } },
3
{ pid: 1, coordinates: { x: null, y: "22", f: null } },
4
{ pid: 1, coordinates: { x: null, y: null, f: "2" } },
5
{ pid: 2, coordinates: { x: "23", y: null, f: null } },
6
{ pid: 2, coordinates: { x: null, y: "62", f: null } },
7
{ pid: 2, coordinates: { x: null, y: null, f: "15" } },
8
];
9
10
const result = Object.values(
11
originalArray.reduce((r, o) => {
12
r[o.pid] ??= { pid: o.pid };
13
r[o.pid].coordinates = {
14
r[o.pid].coordinates,
15
Object.entries(o.coordinates).reduce(
16
(r, [k, v]) => (v && (r[k] = v), r),
17
{}
18
),
19
};
20
return r;
21
}, {})
22
);
23
24
console.log(result);
Relevant Documentations: