I’m struggling to write a reducer function for the nested object that I have.
{ "queryResult": [{ "__typename": "Parent", "_id": "ABC", "items": [{ "__typename": "Child", "_id": "123", "subitems": [{ "__typename": "Grandchild", "_id": "abc", }, { "__typename": "Grandchild", "_id": "def", }, { "__typename": "Grandchild", "_id": "ghi", }, { "__typename": "Grandchild", "_id": "jkl", }, { "__typename": "Grandchild", "_id": "mno", }, { "__typename": "Grandchild", "_id": "pqr", }] }, { "__typename": "Child", "_id": "456", "subitems": [{ "__typename": "Grandchild", "_id": "aaa", }, { "__typename": "Grandchild", "_id": "bbb", }, { "__typename": "Grandchild", "_id": "ccc", }, { "__typename": "Grandchild", "_id": "ddd", }] }, { "__typename": "Child", "_id": "789", "subitems": [{ "__typename": "Grandchild", "_id": "eee", }] }] }] }
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:
"subitems": [{ "__typename": "Grandchild", "_id": "aaa", }, { "__typename": "Grandchild", "_id": "bbb", }, { "__typename": "Grandchild", "_id": "ccc", }, { "__typename": "Grandchild", "_id": "ddd", }]
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:
const data = { "queryResult": [ { "__typename": "Parent", "_id": "ABC", "items": [ { "__typename": "Child", "_id": "123", "subitems": [ { "__typename": "Grandchild", "_id": "abc" }, { "__typename": "Grandchild", "_id": "def" }, { "__typename": "Grandchild", "_id": "ghi" }, { "__typename": "Grandchild", "_id": "jkl" }, { "__typename": "Grandchild", "_id": "mno" }, { "__typename": "Grandchild", "_id": "pqr" } ] }, { "__typename": "Child", "_id": "456", "subitems": [ { "__typename": "Grandchild", "_id": "aaa" }, { "__typename": "Grandchild", "_id": "bbb" }, { "__typename": "Grandchild", "_id": "ccc" }, { "__typename": "Grandchild", "_id": "ddd" } ] }, { "__typename": "Child", "_id": "789", "subitems": [ { "__typename": "Grandchild", "_id": "eee" } ] } ] } ] }; const res = data.queryResult.reduce((acc,parent) => { const { _id:parentId, items } = parent; items.forEach(({_id:itemId, subitems}) => { acc[`${parentId}-${itemId}`] = subitems; }); return acc; }, {}); console.log(res);