Dynamic deep selection for a JavaScript object

前端 未结 4 1075
伪装坚强ぢ
伪装坚强ぢ 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:46

    You can write a little function to split the string and then access each piece in turn. For example:

    function getProperty(propname, object)
    {
        var props = propname.split('.');
        var obj = object;
        for (var i=0; i

    Obviously it nees a little extra coding to check for null objects, valid properties, etc.

提交回复
热议问题