使用lodash列出所有可能的路径

Paw*_*ski 7 javascript lodash

我想列出导致叶子的所有物体路径

例:

var obj = {
 a:"1",
 b:{
  foo:"2",
  bar:3
 },
 c:[0,1]
}
Run Code Online (Sandbox Code Playgroud)

结果:

"a","b.foo","b.bar", "c[0]","c[1]"
Run Code Online (Sandbox Code Playgroud)

我想找到简单易读的解决方案,最好使用lodash.

bin*_*max 5

不使用lodash,但这里是递归的:

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;
}
Run Code Online (Sandbox Code Playgroud)


Nic*_*ick 5

这是一个我可以想到的以多种方式使用lodash的解决方案:

function paths(obj, parentKey) {
  var result;
  if (_.isArray(obj)) {
    var idx = 0;
    result = _.flatMap(obj, function (obj) {
      return paths(obj, (parentKey || '') + '[' + idx++ + ']');
    });
  }
  else if (_.isPlainObject(obj)) {
    result = _.flatMap(_.keys(obj), function (key) {
      return _.map(paths(obj[key], key), function (subkey) {
        return (parentKey ? parentKey + '.' : '') + subkey;
      });
    });
  }
  else {
    result = [];
  }
  return _.concat(result, parentKey || []);
}
Run Code Online (Sandbox Code Playgroud)

编辑:如果您真的只想要叶子,请result在最后一行返回。

  • 我认为这不会奏效。“ flatMapDeep”的“ Deep”部分是指展平操作,而不是地图操作。要查看此内容,请尝试运行`(function(){var _ = require('lodash'); console.log(_。flatMapDeep({a:{b:1}}},function(v,k){return k; })}})();`。这将打印`['a']`而不是`['a','b']`。 (2认同)