List all possible paths using lodash

前端 未结 6 1062
终归单人心
终归单人心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-18 00:26

    Feeding that object through this function should do it I think.

    recursePaths: function(obj){
    var result = [];
    //get keys for both arrays and objects
    var keys = _.map(obj, function(value, index, collection){
        return index;
    });
    
    
    //Iterate over keys
    for (var key in keys) {
        //Get paths for sub objects
        if (typeof obj[key] === 'object'){
            var paths = allPaths(obj[key]);
            for (var path in paths){
                result.push(key + "." + path);
            }
        } else {
            result.push(key);
        }
    }
    
    return result;
    }
    

提交回复
热议问题