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 Parents. Every Parent has items, and every item has subitems with their .ids.
How to write a reducer that would reduce the queryResult by taking in the parentId and the itemId and returning the array of subitems? 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);