Dynamic deep selection for a JavaScript object

前端 未结 4 1102
伪装坚强ぢ
伪装坚强ぢ 2020-12-30 12:54

With a single property this is fairly easy:


var jsonobj = {
    \"test\": \"ok\"
}
var propname = \"test\";
// Will alert \"ok\"
alert(jsonobj[propname]);
<         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-30 13:36

    This works, but rather suckily uses eval so I'm not recommending it's use:

    var jsonobj = {
        "test": {
            "test2": "ok"
        }
    }
    var propname = "test.test2";
    alert(eval("jsonobj." + propname));
    ​
    

    Try it here: http://jsfiddle.net/TAgsU/

提交回复
热议问题