简体   繁体   中英

How to get nested objects in javascript by an string as a bracket notation?

I want a method in javascript that gets a string as its arguments and return a value from a nested object like as:

 var obj = { place: { cuntry: 'Iran', city: 'Tehran', block: 68, info: { name :'Saeid', age: 22 } } }; function getValue(st) { // st: 'place[info][name]' return obj['place']['info']['name'] // or obj.place.info.name } 

One possible solution for your use case:

function getValue(st, obj) {
    return st.replace(/\[([^\]]+)]/g, '.$1').split('.').reduce(function(o, p) { 
        return o[p];
    }, obj);
}

console.log( getValue('place[info][name]', obj) );  // "Saeid"
console.log( getValue('place.info.age', obj) );     // 22

Can you get your input in the form of "['a']['b']['c']"?

function getValue(st) {
  // st: "['place']['info']['name']"
  return eval("obj"+st);
}

You can apply transformation to any strings and get the result.

EDIT:

DO NOT Use Eval directly in your code base. Its evil!

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