I’m struggling to write a reducer function for the nested object that I have.
JavaScript
x
53
53
1
{
2
"queryResult": [{
3
"__typename": "Parent",
4
"_id": "ABC",
5
"items": [{
6
"__typename": "Child",
7
"_id": "123",
8
"subitems": [{
9
"__typename": "Grandchild",
10
"_id": "abc",
11
}, {
12
"__typename": "Grandchild",
13
"_id": "def",
14
}, {
15
"__typename": "Grandchild",
16
"_id": "ghi",
17
}, {
18
"__typename": "Grandchild",
19
"_id": "jkl",
20
}, {
21
"__typename": "Grandchild",
22
"_id": "mno",
23
}, {
24
"__typename": "Grandchild",
25
"_id": "pqr",
26
}]
27
}, {
28
"__typename": "Child",
29
"_id": "456",
30
"subitems": [{
31
"__typename": "Grandchild",
32
"_id": "aaa",
33
}, {
34
"__typename": "Grandchild",
35
"_id": "bbb",
36
}, {
37
"__typename": "Grandchild",
38
"_id": "ccc",
39
}, {
40
"__typename": "Grandchild",
41
"_id": "ddd",
42
}]
43
}, {
44
"__typename": "Child",
45
"_id": "789",
46
"subitems": [{
47
"__typename": "Grandchild",
48
"_id": "eee",
49
}]
50
}]
51
}]
52
}
53
queryResult
can have many Parent
s. Every Parent
has item
s, and every item
has subitem
s with their .id
s.
How to write a reducer that would reduce the queryResult
by taking in the parentId
and the itemId
and returning the array of subitem
s? For example, for parentId
= ABC
and for the itemId
= 456
I need a result that looks like:
JavaScript
1
14
14
1
"subitems": [{
2
"__typename": "Grandchild",
3
"_id": "aaa",
4
}, {
5
"__typename": "Grandchild",
6
"_id": "bbb",
7
}, {
8
"__typename": "Grandchild",
9
"_id": "ccc",
10
}, {
11
"__typename": "Grandchild",
12
"_id": "ddd",
13
}]
14
Note: all the IDs are random, there is no logic there whatsoever.
Advertisement
Answer
You can reduce queryResult
to a map of parentId-itemId as the key
and subitems as the value
as follows:
JavaScript
1
49
49
1
const data = {
2
"queryResult": [
3
{
4
"__typename": "Parent",
5
"_id": "ABC",
6
"items": [
7
{
8
"__typename": "Child",
9
"_id": "123",
10
"subitems": [
11
{ "__typename": "Grandchild", "_id": "abc" },
12
{ "__typename": "Grandchild", "_id": "def" },
13
{ "__typename": "Grandchild", "_id": "ghi" },
14
{ "__typename": "Grandchild", "_id": "jkl" },
15
{ "__typename": "Grandchild", "_id": "mno" },
16
{ "__typename": "Grandchild", "_id": "pqr" }
17
]
18
},
19
{
20
"__typename": "Child",
21
"_id": "456",
22
"subitems": [
23
{ "__typename": "Grandchild", "_id": "aaa" },
24
{ "__typename": "Grandchild", "_id": "bbb" },
25
{ "__typename": "Grandchild", "_id": "ccc" },
26
{ "__typename": "Grandchild", "_id": "ddd" }
27
]
28
},
29
{
30
"__typename": "Child",
31
"_id": "789",
32
"subitems": [
33
{ "__typename": "Grandchild", "_id": "eee" }
34
]
35
}
36
]
37
}
38
]
39
};
40
41
const res = data.queryResult.reduce((acc,parent) => {
42
const { _id:parentId, items } = parent;
43
items.forEach(({_id:itemId, subitems}) => {
44
acc[`${parentId}-${itemId}`] = subitems;
45
});
46
return acc;
47
}, {});
48
49
console.log(res);