我想列出导致叶子的所有物体路径
例:
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.
不使用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)
这是一个我可以想到的以多种方式使用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在最后一行返回。
| 归档时间: |
|
| 查看次数: |
3192 次 |
| 最近记录: |