使用变量动态访问对象属性 [英] Dynamically access object properties using a variable

查看:32
本文介绍了使用变量动态访问对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大对象,其中嵌套了多个对象.我有一个函数,它将采用对象之一的键,并且我想向被调用的子对象添加一个新属性.类似于 https://jsfiddle.net/cf15xdfm/2/

I have a large object with multiple objects nested within it. I have a function that will take the key of one of the objects, and I want to add a new property to the sub-object that is called. Something like https://jsfiddle.net/cf15xdfm/2/

var my_object = {
    object1: {
    key: 'value',
    key2: 'value2'
  },
  object2: {
    key: 'othervalue',
    key2: 'another'
  }
}

function doSomething(obj_key) {
    // add a new property to the object 
  my_object.obj_key.new_prop = 'this_new_prop';
}

doSomething('object1');

console.dir(my_object);

如何在 doSomething 方法中引用变量 obj_key ,以便可以更改所需的对象?

How do I reference the variable obj_key in the doSomething method so that I can alter the desired object?

推荐答案

使用括号符号来访问动态键

var my_object = {
    object1: {
    key: 'value',
    key2: 'value2'
  },
  object2: {
    key: 'othervalue',
    key2: 'another'
  }
}

function doSomething(obj_key) {
    // add a new property to the object 
  my_object[obj_key].new_prop = 'this_new_prop'; // using bracket notation here
}

doSomething('object1');

console.dir(my_object);

这篇关于使用变量动态访问对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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