使用lodash列出所有可能的路径 [英] List all possible paths using lodash

查看:432
本文介绍了使用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.

这篇关于使用lodash列出所有可能的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆