简体   繁体   中英

how can I get something in Object with a Array?

I want to change value in a Object,but this Object is nest,like this

Obj = {
  'a': {
    'b': {
      'c': {
        'name': 'bob'
      }
    }
  }
}

and there is a Array:
['a','b','c']
I want get name with this array
how can I change this array to obj['a']['b']['c']['name'] ?
Must consider the nested object different layers? how can I do 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 ) /***************************************************************/ // we can do also something like that : var Obj2 = { 'a': { 'b': { 'c': { 'name': ['bob' , 'marc' , 'jane' , 'lisa'] } } } } var keyPath2 = 'abcname.2' var result2 = keyPath2.split('.').reduce(function( transformed , value){ return transformed[value]; } , Obj2) log( 'result2\\t : ' + result2 ) /***************************************************************/ // and using it in a function var ns = function( keyPath , context , splitter){ var _keyPath = keyPath.split(splitter|| '.'); return _keyPath.reduce(function( transformed , value){ return transformed[value]; } , context) }; var keyPath3 = 'abcname.3'; var result3 = ns( keyPath3 , Obj2 ); log( 'result3\\t : ' + result3) 
 <div id='dbg'><div> 

That's a classic case for lodash , specifically the _.get method

 var Obj = { 'a': { 'b': { 'c': { 'name': 'bob' } } } } var keyPath = ['a','b','c']; alert(_.get(Obj, keyPath).name); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM