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

问题描述:

我想列出导致叶子的所有对象路径

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

示例:

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

结果:

"a","b.foo","b.bar", "c[0]","c[1]"

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

I would like to find simple and readable solution, best using lodash.

这是一个使用lodash的解决方案,我想到的方法很多:

Here is a solution that uses lodash in as many ways as I can think of:

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 || []);
}

编辑:如果你真的只想离开,只需返回结果在最后一行。

If you truly want just the leaves, just return result in the last line.