Javascript:通过将路径作为字符串传递给对象来从对象中获取深层值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8817394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:39:21  来源:igfitidea点击:

Javascript: Get deep value from object by passing path to it as string

javascriptsyntaxpath

提问by 7elephant

Possible Duplicate:
Accessing nested JavaScript objects with string key

可能的重复:
使用字符串键访问嵌套的 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' }
};

I want to access the value of obj.foo.bar by suppling the string "foo.bar" to the function.

我想通过向函数提供字符串“foo.bar”来访问 obj.foo.bar 的值。

function(obj, path) {
  // Path can be "foo.bar", or just "foo".
}

Thanks!

谢谢!

采纳答案by qiao

Consider this:

考虑一下:

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'))

回答by Tadeck

This works correctly:

这正常工作:

var deep_value = function(obj, path){
    for (var i=0, path=path.split('.'), len=path.length; i<len; i++){
        obj = obj[path[i]];
    };
    return obj;
};

Here is the proof / demo: jsfiddle.net/tadeck/5Pt2q/13/

这是证明/演示:jsfiddle.net/tadeck/5Pt2q/13/

EDIT: I have removed redundant variables, shortened the code.

编辑:我删除了冗余变量,缩短了代码。

回答by fyr

You mean something like this ? It is a recursive version

你的意思是这样的?这是一个递归版本

function recLookup(obj, path) {
    parts = path.split(".");
    if (parts.length==1){
        return obj[parts[0]];
    }
    return recLookup(obj[parts[0]], parts.slice(1).join("."));
}

See http://jsfiddle.net/kExSr/

http://jsfiddle.net/kExSr/

回答by Dan D.

something like:

就像是:

function(obj, path) {
  var current=obj; 
  path.split('.').forEach(function(p){ current = current[p]; }); 
  return current;
}

回答by T.J. Crowder

You'd want to split the string on the dot and then repeatedly index into the object, e.g. along the lines of:

您想在点上拆分字符串,然后重复索引到对象中,例如沿着以下几行:

function goDeep(obj, path) {
    var parts = path.split('.'),
        rv,
        index;
    for (rv = obj, index = 0; rv && index < parts.length; ++index) {
        rv = rv[parts[index]];
    }
    return rv;
}

Live example

活生生的例子

That works because you can access the property of an object in a couple of different ways: There's dotted syntax using a literal (obj.foo), and there's bracketed syntax using a string (obj["foo"]). In the latter case, the string can be the result of any expression, it doesn't have to be a string literal. In in all of the, rvis set to the same value:

这是有效的,因为您可以通过几种不同的方式访问对象的属性:使用文字 ( obj.foo)的点式语法,使用字符串 ( obj["foo"])的方括号语法。在后一种情况下,字符串可以是任何表达式的结果,它不必是字符串文字。在所有的中,rv设置为相同的值:

rv = obj.foo.bar;
// Or
rv = obj.foo["bar"];
// Or
f = "foo";
rv = obj[f].bar;
// Or
s = "b";
rv = obj.foo[s + "ar"];