简体   繁体   English

如何通过字符串作为括号表示法来获取javascript中的嵌套对象?

[英]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: 我想要javascript中的方法,该方法获取字符串作为其参数,并从嵌套对象返回值,例如:

 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']"? 您能否以“ ['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. 不要在代码库中直接使用Eval。 Its evil! 它的邪恶!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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