javascript - How can I set data in object using a string as the selector? -


let's have global object that's accessible 1 function accepts string.

the following defined inside function.

function setitem(string, val) {      var scope = [{       apple : true,        test : 'aa'       },{       apple : false,       test : 'bb'     }];     var obj = {         'deep' : scope     }     obj.string = val;     return obj.string; }); 

now want first item, overwrite data.

setitem('scope[0].apple', 'apple off');

obviously above isn't going work when trying set variable, i'm wondering if there's way evaluate string value can contain dotnotated , index selectors?

it can done eval.

function setitem(string, val) {    var scope = [{      apple: true,      test: 'aa'    }, {      apple: false,      test: 'bb'    }];    var obj = {      'deep': scope    }    eval(string + ' = ' + json.stringify(val));    return eval(string);  };  alert(setitem('scope[0].apple', 'apple off'));


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -