I have an array of objects.
I want to merge the objects into a single array by same key. At that time, I also want to include other value in the array together.
It doesn't matter whether the merged array is an array or an object.
Current array:
[
{
"datetime": "2022-01-10",
"a": 0.5,
"b": 80.6,
"c": 1002.2
},
{
"datetime": "2022-01-11",
"a": 0.7,
"b": 80.4,
"c": 1002.4
},
{
"datetime": "2022-01-12",
"a": 0.4,
"b": 80.2,
"c": 1002.3
}
]
Expected result:
[
[
["2022-01-10", 0.5], ["2022-01-11", 0.7], ["2022-01-12", 0.4]
],
[
["2022-01-10", 80.6], ["2022-01-11", 80.4], ["2022-01-12", 1002.4]
],
[
["2022-01-10", 1002.2], ["2022-01-11", 1002.4], ["2022-01-12", 1002.3]
]
]
or
{
"a": [
["2022-01-10", 0.5], ["2022-01-11", 0.7], ["2022-01-12", 0.4]
],
"b": [
["2022-01-10", 80.6], ["2022-01-11", 80.4], ["2022-01-12", 1002.4]
],
"c": [
["2022-01-10", 1002.2], ["2022-01-11", 1002.4], ["2022-01-12", 1002.3]
]
}
I use forEach()
and it works.
But I want to know if there are other ways.
const foo = [[], [], []];
json.forEach((item) => {
const [a, b, c] = foo;
a.push([item.datetime, item.a]);
b.push([item.datetime, item.b]);
c.push([item.datetime, item.c]);
});