Javascript Object notation with variable

五迷三道 提交于 2019-11-28 09:16:07

问题


My PHP script specs.php outputs the following:

{
    "hd": {
        "dimensions": [
            "1920x1080",
            "1920x1080",
            "1920x1080" 
        ],
        "sizes": [
            "603 KB",
            "265 KB",
            "438 KB" 
        ] 
    },
    "medium": {
        "dimensions": [
            "800x530",
            "800x530",
            "800x530" 
        ],
        "sizes": [
            "198 KB",
            "105 KB",
            "152 KB" 
        ] 
    },
    "status": "success"
}

With jQuery I load in the JSON and assign it to specs_obj
I can access the first item's "medium" "sizes" with specs_obj. medium.sizes[0]
How can I use a variable in the dot notation?

var specs_obj;
$.post("specs.php", {},
    function(data) {
        if (data.status == "success") {
                specs_obj = data;
                writeSizes("medium");
        } else {}
    }, "json"
);

function writeSizes(preset) {
    // test get medium dimensions from first file
    var size = specs_obj. medium.sizes[0];
    // var size = specs_obj.preset.sizes[0];
}

回答1:


You can't use a variable in the dot notation, but you can use brackets notation:

var size = specs_obj[preset].sizes[0];

If preset contains the string "medium", that's functionally identical to:

var size = specs_obj.medium.sizes[0];


来源:https://stackoverflow.com/questions/4255389/javascript-object-notation-with-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!