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

时间:2021-12-22 19:15:44

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!

谢谢!

5 个解决方案

#1


38  

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

#2


62  

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.

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

#3


7  

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/

#4


6  

something like:

就像是:

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

#5


3  

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, rv is 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"];

#1


38  

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

#2


62  

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.

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

#3


7  

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/

#4


6  

something like:

就像是:

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

#5


3  

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, rv is 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"];