Javascript assign value to element in nested object without knowing level -


say have object this:

a : {   a1 : {     a2: true   }  } 

and have path saved in array:

[a1, a2] 

if want assign value a["a1"]["a2"], easy:

a["a1"]["a2"] = true; 

however when have 3 level path this:

[a1, a2, a3] 

i have manually write code this:

a["a1"]["a2"]["a3"] = true; 

is there way automatically handle level of paths don't have make explicit every single case?

note "a" can quite complex want assign value specific element , without touching rest.

thanks in advance!

there several ways access properties:

use loop:

var obj = {         a1 : {             a2: { a3: 'test' }         }      },     = 0,     keypath = ['a1', 'a2', 'a3'],     len = keypath.length;      (; < len; i++) {         obj = obj[keypath[i]];     }      console.log(obj); 

with eval (i don't recommend however):

var obj = {             a1 : {                 a2: { a3: 'test' }             }          };  var value = eval('obj.' + keypath.join('.'));  console.log(value); 

you use same approach set property @ specific key path:

function setproperty(obj, keypath, value) {     var = 0,         len = keypath.length - 1;      (; < len; i++) {         obj = obj[keypath[i]];     }      obj[keypath[i]] = value; } 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -