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

问题描述

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

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

如果我想要 'foo' 与 'bee',我可以只做 arr[variable] - 这很简单,函数就是这样做的.

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

但是如果我想得到 arr.bar.baz 又名 arr[bar][baz] 怎么办?

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

我可以向 getter 函数传递什么来让我这样做(当然也可以让我使用相同的函数获取非嵌套属性).

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

我试过 getter('bar.baz')getter('[bar][baz]') 但没有用.

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

我想我可以解析点或括号(例如:在 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函数签名改为getter('bar', 'baz')

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中如何动态获取对象的嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 16:09