Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively find all children from parent menu

I have a JSON structure like this:

[
    {"menuId":"1001","depth":"1","parentId":"0"},
    {"menuId":"1002","depth":"1","parentId":"0"},
    {"menuId":"1003","depth":"2","parentId":"1001"},
    {"menuId":"1004","depth":"2","parentId":"1001"},
    {"menuId":"1005","depth":"3","parentId":"1003"}, 
    {"menuId":"1006","depth":"3","parentId":"1004"}, 
    {"menuId":"1007","depth":"4","parentId":"1006"}, 
    {"menuId":"1008","depth":"4","parentId":"1006"}, 
    {"menuId":"1009","depth":"5","parentId":"1008"}
]

So I need a (probably) recursive function, that will find all children of one menuId, even the deep nested ones.

So let's say I wanna findChildrens('1004'). This should return the following result:

['1006', '1007', '1008', '1009']

because each of this menus can be referenced back to 1004. No specific order is required. The depth can go indefnitly.

like image 397
Wolfdog Avatar asked Dec 28 '25 23:12

Wolfdog


2 Answers

You could take an iterative and recursive approach by checking the parentId and get the menuId for the result set. Then add the new children as well.

function getChildren(array, id) {
    return array.reduce((r, { menuId, parentId }) => {
        if (parentId === id) {
            r.push(menuId, ...getChildren(array, menuId));
        }
        return r;
    }, []);
}

var data = [{ menuId: "1001", depth: "1", parentId: "0" }, { menuId: "1002", depth: "1", parentId: "0" }, { menuId: "1003", depth: "2", parentId: "1001" }, { menuId: "1004", depth: "2", parentId: "1001" }, { menuId: "1005", depth: "3", parentId: "1003" }, { menuId: "1006", depth: "3", parentId: "1004" }, { menuId: "1007", depth: "4", parentId: "1006" }, { menuId: "1008", depth: "4", parentId: "1006" }, { menuId: "1009", depth: "5", parentId: "1008" }],
    result = getChildren(data, '1004');

console.log(result);
like image 75
Nina Scholz Avatar answered Dec 30 '25 12:12

Nina Scholz


You can just use normal recursion like this.

  var k = 
         [{"menuId":"1001","depth":"1","parentId":"0"},
          {"menuId":"1002","depth":"1","parentId":"0"},
          {"menuId":"1003","depth":"2","parentId":"1001"},
          {"menuId":"1004","depth":"2","parentId":"1001"},
          {"menuId":"1005","depth":"3","parentId":"1003"}, 
          {"menuId":"1006","depth":"3","parentId":"1004"}, 
          {"menuId":"1007","depth":"4","parentId":"1006"}, 
          {"menuId":"1008","depth":"4","parentId":"1006"}, 
          {"menuId":"1009","depth":"5","parentId":"1008"}]
        var res = [];
          var findChildren = function(id){
            k.forEach(obj => {
              if(obj.parentId === id){
                  res.push(obj.menuId);
        		  findChildren(obj.menuId)
        		}
        	})
        }
    
        findChildren('1004');
        console.log(res);
like image 23
sridhar.. Avatar answered Dec 30 '25 13:12

sridhar..