在JavaScript我怎么能动态获取对象的嵌套属性 [英] In javascript how can I dynamically get a nested property of an object

查看:384
本文介绍了在JavaScript我怎么能动态获取对象的嵌套属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var arr = { foo : 1, bar: { baz : 2 }, bee : 3 }

function getter(variable) {
  return arr[variable];
}

如果我想'富'VS'蜜蜂'我可以做改编[可变] - 这很容易,而且功能确实是

If I want 'foo' vs 'bee' I can just do arr[variable] - that's easy, and the function does that.

但是,如果我想获得 arr.bar.baz AKA 改编什么[巴] [巴兹]

But what if I want to get arr.bar.baz AKA arr[bar][baz]?

我可以通过吸气剂的功能,可以让我做那是什么,(当然也让我使用相同的函数来获取非嵌套的属性)。

What can I pass to the getter function that will let me do that, (and of course also let me get non-nested properties using the same function).

我试过吸气剂('bar.baz')吸气剂('[巴] [巴兹]')但那些没有工作。

I tried getter('bar.baz') and getter('[bar][baz]') but those didn't work.

我想我可以解析为点或括号(喜欢这里:<一href=\"http://stackoverflow.com/questions/4343028/in-javascript-test-for-property-deeply-nested-in-object-graph\">In JavaScript中,测试性能深深嵌套在对象图?)。是否有一个更清洁的方式? (当然除了EVAL)。

I suppose I can parse for dots or brackets (like here: In javascript, test for property deeply nested in object graph?). Is there a cleaner way? (Besides eval of course.)

尤其是因为我需要在一个循环中深深设置正确很多很多次了一堆数组中的元素。

Especially because I need to get the deeply set properly many many times in a loop for a bunch of array elements.

推荐答案

如何变化的getter函数签名吸气剂('巴','巴兹')而不是

How about change the getter function signature as getter('bar', 'baz') instead

function getter() {
  var v = arr;
  for(var i=0; i< arguments.length; i++) {
    if(!v) return null;
    v = v[arguments[i]];
  }
  return v;
}

PS。没有测试,但你的想法;)

ps. didn't test, but you get the idea ;)

这篇关于在JavaScript我怎么能动态获取对象的嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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