List all possible paths using lodash

前端 未结 6 1059
终归单人心
终归单人心 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:21

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

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

提交回复
热议问题