javascript - how can I get something in Object with a Array? -
i want change value in object,but object nest,like
obj = { 'a': { 'b': { 'c': { 'name': 'bob' } } } }
and there array:
['a','b','c']
want name
array
how can change array obj['a']['b']['c']['name']
?
must consider nested object different layers? how can this?
or in pure javascript :
['a','b','c', 'name' ].reduce(function( t , v ){ return t[v];} , obj)
el = document.getelementbyid('dbg'); var json = function(val){ return json.stringify(val) }; var log = function(val){el.innerhtml += '<div><pre>' + val + '</pre><div>'} /****************************************************************/ var obj = { 'a': { 'b': { 'c': { 'name': 'bob' } } } } var keypath = ['a','b','c', 'name' ]; var result = keypath.reduce(function( transformed , value){ return transformed[value]; } , obj) log( 'result\t : ' + result ) /***************************************************************/ // can : var obj2 = { 'a': { 'b': { 'c': { 'name': ['bob' , 'marc' , 'jane' , 'lisa'] } } } } var keypath2 = 'a.b.c.name.2' var result2 = keypath2.split('.').reduce(function( transformed , value){ return transformed[value]; } , obj2) log( 'result2\t : ' + result2 ) /***************************************************************/ // , using in function var ns = function( keypath , context , splitter){ var _keypath = keypath.split(splitter|| '.'); return _keypath.reduce(function( transformed , value){ return transformed[value]; } , context) }; var keypath3 = 'a.b.c.name.3'; var result3 = ns( keypath3 , obj2 ); log( 'result3\t : ' + result3)
<div id='dbg'><div>
Comments
Post a Comment