if i already know an object`s structure,how can i eval the right value to the object?(javascript) -


if have object this:

let obj = {   a:{     b:{       c:{         d:{          e:'nonono'        }      }    }  } } 

and know structure of object that:

now want change innermost layer of object, "e" property. want assign value "e". don't want these ways below:

  1. obj.a.b.c.d.e = 'another value';
  2. var str1 = 'a.b.c.d.e'; obj[str1[0]][str[1]][str[2]][str[3]][str[4]];
  3. var str1 = 'obj.a.b.c.d.e'; var str = str1 + "='another value'"; eval(str);

above these, can change property 'e' of object's value, think it`s not grace express mean.

if have array that: var arr= [a,b,c,d,e], want recursion function find innermost layer of object, try, if reach innermost layer of object, lose quote of object..... can't change object's value want. think run these code, if can me run.

let obj = {    a: {      b: {        c: {          d: {            e: 'nonono'          }        }      }    }  }  let arr = ['a', 'b', 'c', 'd', 'e'];  let funkeepcite = (obj, index) => {    if (obj[arr[index]]) {      funkeepcite(obj[arr[index]], index + 1);    } else {      obj = 'test'    }  }  funkeepcite(obj, 0)  console.log('the result', obj)

i can't change value, think lose quote of object, answer of question use for .. in, , can keep quote of object, confused of these.

you can't assign obj local variable, have assign property. recurse until second-to-last index, use last 1 assignment:

function funkeepcite(obj,index) {   if (index < arr.length - 1) {     funkeepcite(obj[arr[index]], index+1);   } else if (index < arr.length) {     obj[arr[index]] = 'test';   } else     throw new rangeerror("there must @ least 1 property name in array");   } } 

alternatively, use recursion return value , assign:

function funkeepcite(obj, index) {   if (index < arr.length) {     obj[arr[index]] = funkeepcite(obj[arr[index]], index+1);     return obj;   } else {     return 'test';   } } 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -