I want to build an object that takes the age
as the key and the value of that key would be an array with names corresponding to that.
The Array:
const arr = [{
name: "Rita",
age: 23
},
{
name: "John",
age: 25
},
{
name: "Barbara",
age: 23
},
]
What I want as an outcome:
const obj = {
23: ["Rita", "Barbara"],
25: ["John"]
}
I've built something with reduce
but is breaking saying ...(acc[curr.age] || {}), curr.name
is not iterable.
My suspicious is that it doesn't like having the initial as an empty object ({}
). But I can't have an initial with keys because they should be dynamic.
This is my non-working solution:
const obj = arr.reduce((acc, curr) => {
return {
...(acc || {}),
[curr.age]: [...(acc[curr.age] || {}), curr.name]
}
}, {})
The error is on ...(acc[curr.age] || {})
. acc[curr.age]
is supposed to be an array, isn't it? Take a look at the final result you expect.
const obj = arr.reduce((acc, curr) => {
return {
...(acc || {}),
[curr.age]: [...(acc[curr.age] || []), curr.name]
}
}, {})
Check it online.