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

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

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
user101289
  • 9,888
  • 15
  • 81
  • 148
  • Also [this one](https://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-by-name-as-string). – Jared Smith Mar 06 '18 at 18:00

3 Answers3

3

Make use of brackets notation for accessing dynamic keys

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);
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
0

You can use:

my_object[obj_key].new_prop='this_new_prop';
Boluc Papuccuoglu
  • 2,318
  • 1
  • 14
  • 24
0

You can call properties as string like this:

obj['property_name']

So you should do this:

my_object[obj_key].new_prop = 'this_new_prop';

Edit: Sorry didn't see the answer was already there