I have data that comes back from an API as an array of Objects.
JavaScript
x
20
20
1
const data =
2
[
3
4
{
5
name: "Charles",
6
age: 42,
7
height: 76
8
},
9
{
10
name: "Jim",
11
age: 32,
12
height: 56
13
},
14
{
15
name: "Ed",
16
age: 22,
17
height: 76
18
}
19
]
20
rather than just returning that, return data
, I’d like to have it where the name is the key
so that I can do a lookup on data
, like data["Jim"]
and get the object
back.
JavaScript
1
18
18
1
const data =
2
[
3
{
4
"Charles":
5
{
6
age: 42,
7
height: 76
8
},
9
},
10
{
11
"Jim":
12
{
13
age: 32,
14
height: 56
15
},
16
}
17
]
18
how can I manipulate the data to come back that way after getting it back from the API in the original format listed first?
Advertisement
Answer
What you’re looking for is this
JavaScript
1
2
1
const result = data.reduce((acc, curr) => ({acc, [curr.name]: {age: curr.age, height: curr.height}}), {});
2
now you can access like result['Jim']
. You needed an object, not an array.