Having a JSON in this format:
JavaScript
x
26
26
1
[{
2
name: "A",
3
country: "X",
4
countryID: "02",
5
value: 15
6
},
7
{
8
name: "A",
9
country: "Y",
10
countryID: "01",
11
value: 25
12
},
13
{
14
name: "B",
15
country: "X",
16
countryID: "02",
17
value: 35
18
},
19
{
20
name: "B",
21
country: "Y",
22
countryID: "01",
23
value: 45
24
}
25
]
26
how can I combine the objects by name
, country
, and countryID
in Javascript to get the following JSON output?
JavaScript
1
14
14
1
[{
2
country: "Y",
3
countryID: "01",
4
valueA: 25,
5
valueB: 45
6
},
7
{
8
country: "X",
9
countryID: "02",
10
valueA: 15,
11
valueB: 35
12
}
13
]
14
Advertisement
Answer
Using Array.prototype.reduce
, you can group array items by country
and countryID
key-value pairs and store the result to the object values of that generated key as follows.
JavaScript
1
38
38
1
const input = [{
2
name: "A",
3
country: "X",
4
countryID: "02",
5
value: 15
6
},
7
{
8
name: "A",
9
country: "Y",
10
countryID: "01",
11
value: 25
12
},
13
{
14
name: "B",
15
country: "X",
16
countryID: "02",
17
value: 35
18
},
19
{
20
name: "B",
21
country: "Y",
22
countryID: "01",
23
value: 45
24
}
25
];
26
27
const groupBy = input.reduce((acc, cur) => {
28
const key = `${cur.country}_${cur.countryID}`;
29
acc[key] ? acc[key][`value${cur.name}`] = cur.value : acc[key] = {
30
country: cur.country,
31
countryID: cur.countryID,
32
['value' + cur.name]: cur.value
33
};
34
return acc;
35
}, {});
36
37
const output = Object.values(groupBy);
38
console.log(output);