Javascript:通过将路径作为字符串传递给对象来从对象中获取深层值 [英] Javascript: Get deep value from object by passing path to it as string

查看:27
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆