I have an array of object that look this,
const data = [
{
key: "id1",
name: "Category 1",
curr: 0,
total: 0,
nodes: [
{
key: "id2",
name: "Applications",
curr: 20,
total: 30,
nodes: [
{
key: "id3",
name: "Gaming",
curr: 5,
total: 10,
nodes: []
},
{
key: "id4",
name: "Operating System",
curr: 15,
total: 20,
nodes: []
}
]
}
]
},
{
key: "id5",
name: "Category 2",
curr: 0,
total: 0,
nodes: [
{
key: "id6",
name: "Sub Category",
curr: 12,
total: 48,
nodes: [
{
key: "id7",
name: "Inside Sub",
curr: 12,
total: 48,
nodes: []
}
]
}
]
},
{
key: "id8",
name: "Last One",
curr: 0,
total: 0,
nodes: []
}
];
key
property at each level is unique across the entire tree. When I pass in key and this array to a functon, it should increment the curr
value at the matching key level and this increment should go all the way upto level 1. Note that level 0 items should not be updated. So basically when I pass incrementRecursively(data, "id4")
, the output should look like,
const output = [
{
key: "id1",
name: "Category 1",
curr: 0,
total: 0,
nodes: [
{
key: "id2",
name: "Applications",
curr: 21,
total: 30,
nodes: [
{
key: "id3",
name: "Gaming",
curr: 5,
total: 10,
nodes: []
},
{
key: "id4",
name: "Operating System",
curr: 16,
total: 20,
nodes: []
}
]
}
]
},
{
key: "id5",
name: "Category 2",
curr: 0,
total: 0,
nodes: [
{
key: "id6",
name: "Sub Category",
curr: 12,
total: 48,
nodes: [
{
key: "id7",
name: "Inside Sub",
curr: 12,
total: 48,
nodes: []
}
]
}
]
},
{
key: "id8",
name: "Last One",
curr: 0,
total: 0,
nodes: []
}
];
The code that I tried,
const incrementRecursively = (nodes, key) => {
const increment = (nodes, key) => {
nodes.forEach((node) => {
if (node.key === key) {
node.curr++;
}
if (node.nodes.length) {
increment(node, key);
}
});
};
increment(nodes, key);
return nodes;
};
Can someone help how to update the parent and not increment roots value?
3
Answers
Something like this should work:
The idea is to return
true
if the current node has been directly or indirectly incremented so that the parent can update accordingly.You could implement a walker to step through the tree.
I think this code will do the job:
(it’s based on @gog answer and is self-explanatory hopefully)