I need help with this please. I have the following array of objects:
[
{
name: "A",
id: "q1",
history: {
"1:2:3": {a: 0, b: 0, c: 0},
"4:5:6": {a: 1, b: 1, c: 1},
"7:8:9": {a: 2, b: 2, c: 2}
}
},
{
name: "B",
id: "q2",
history: {
"1:2:3": {a: 3, b: 3, c: 3},
"4:5:6": {a: 4, b: 4, c: 4},
"7:8:9": {a: 5, b: 5, c: 5}
}
},
{
name: "C",
id: "q3",
history: {
"1:2:3": {a: 6, b: 6, c: 6},
"4:5:6": {a: 7, b: 7, c: 7},
"7:8:9": {a: 8, b: 8, c: 8}
}
}
]
and I want to obtain the following result:
{
"1:2:3": {
"q1": {a: 0, b: 0, c: 0},
"q2": {a: 3, b: 3, c: 3},
"q3": {a: 6, b: 6, c: 6}
},
"4:5:6": {
"q1": {a: 1, b: 1, c: 1},
"q2": {a: 4, b: 4, c: 4},
"q3": {a: 7, b: 7, c: 7}
},
"7:8:9": {
"q1": {a: 2, b: 2, c: 2},
"q2": {a: 5, b: 5, c: 5},
"q3": {a: 8, b: 8, c: 8}
}
}
I want the result to be an object with 1:2:3, 4:5:6, 7:8:9 the keys.
Some solutions please? Thank you! :)
1 Answer 1
It's a good example of how can one use reduce
const data = [{
name: "A",
id: "q1",
history: {
"1:2:3": {
a: 0,
b: 0,
c: 0
},
"4:5:6": {
a: 1,
b: 1,
c: 1
},
"7:8:9": {
a: 2,
b: 2,
c: 2
}
}
},
{
name: "B",
id: "q2",
history: {
"1:2:3": {
a: 3,
b: 3,
c: 3
},
"4:5:6": {
a: 4,
b: 4,
c: 4
},
"7:8:9": {
a: 5,
b: 5,
c: 5
}
}
},
{
name: "C",
id: "q3",
history: {
"1:2:3": {
a: 6,
b: 6,
c: 6
},
"4:5:6": {
a: 7,
b: 7,
c: 7
},
"7:8:9": {
a: 8,
b: 8,
c: 8
}
}
}
]
const result = data.reduce((acc, item) => {
const keys = Object.keys(item.history);
for (let key of keys) {
acc[key] = {
...(acc[key] || {}),
[item.id]: item.history[key]
}
}
return acc;
}, {})
console.log(result);
answered May 22, 2020 at 21:52
Józef Podlecki
11.4k5 gold badges33 silver badges55 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Explore related questions
See similar questions with these tags.
lang-js
1:2:3:and4:5:6and7:8:9? That's not valid Javascript syntax.