List all possible paths using lodash

前端 未结 6 1115
终归单人心
终归单人心 2021-01-18 00:08

I would like to list all paths of object that lead to leafs

Example:

var obj = {
 a:\"1\",
 b:{
  foo:\"2\",
  bar:3
 },
 c:[0,1]
}

6条回答
  •  生来不讨喜
    2021-01-18 00:11

    Doesn't use lodash, but here it is with recursion:

    var getLeaves = function(tree) {
        var leaves = [];
        var walk = function(obj,path){
            path = path || "";
            for(var n in obj){
                if (obj.hasOwnProperty(n)) {
                    if(typeof obj[n] === "object" || obj[n] instanceof Array) {
                        walk(obj[n],path + "." + n);
                    } else {
                        leaves.push(path + "." + n);
                    }
                }
            }
        }
        walk(tree,"tree");
        return leaves;
    }
    

提交回复
热议问题