从javascript对象属性创建路径 [英] Create path from javascript object property
本文介绍了从javascript对象属性创建路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下javascript对象
Let's say I've got the following javascript object
var obj = {
a:{
b:"value",
c:{
d:"value2"
}
}
}
当用"d"对象(例如,function getPath(obj, d)
)输入时,什么功能输出"a.c.d"字符串?我已经尝试过各种方法,包括对象路径,但它似乎不是设计好的为此
What function would, when input with the "d" object (for example, function getPath(obj, d)
), output the "a.c.d" string? I've tried various things including object-path, but it doesn't seem to be designed for that
推荐答案
您可以使用迭代和递归方法.
You could use an iterative and recursive approach.
function getPath(object, key) {
function iter(o, p) {
if (typeof o === 'object') {
return Object.keys(o).some(function (k) {
return iter(o[k], p.concat(k));
});
}
if (p[p.length - 1] === key) {
path = p;
return true;
}
}
var path = [];
iter(object, []);
return path.join('.');
}
console.log(getPath({ d: { d: { d: { d: 'val' } } } }, 'd'));
console.log(getPath({ a: { b: 'value', c: { d: 'value2' } } }, 'd'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于从javascript对象属性创建路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文