Javascript:通过将路径作为字符串传递给它来从对象获取深层值 [英] Javascript: Get deep value from object by passing path to it as string
本文介绍了Javascript:通过将路径作为字符串传递给它来从对象获取深层值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
使用字符串键访问嵌套的JavaScript对象
也许标题不够明确,我只是不知道如何指定我正在寻找的东西,我的英语非常糟糕,抱歉。
Maybe the title is not clear enough, I just didn't know how to specify what I'm looking for and my English is really bad, sorry.
我'我试图创建返回对象值的函数,但也可以使用嵌套对象。例如:
I'm trying to create function that returns object value, but also plays nice with nested objects. For example:
var obj = {
foo: { bar: 'baz' }
};
我想通过提供字符串foo.bar来访问obj.foo.bar的值到函数。
I want to access the value of obj.foo.bar by suppling the string "foo.bar" to the function.
function(obj, path) {
// Path can be "foo.bar", or just "foo".
}
谢谢!
推荐答案
考虑一下:
var obj = {
foo: { bar: 'baz' }
};
function deepFind(obj, path) {
var paths = path.split('.')
, current = obj
, i;
for (i = 0; i < paths.length; ++i) {
if (current[paths[i]] == undefined) {
return undefined;
} else {
current = current[paths[i]];
}
}
return current;
}
console.log(deepFind(obj, 'foo.bar'))
这篇关于Javascript:通过将路径作为字符串传递给它来从对象获取深层值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文