Javascript object designation with variable

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 JSON and assign it to specs_obj.
I can access the first elements "average" "size" with specs_obj. medium.sizes [0]
How to use a variable in 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];
}
+3
source share
1 answer

You cannot use a variable in dotted notation, but you can use a notation in parentheses:

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

If it presetcontains the string "medium", which is functionally identical:

var size = specs_obj.medium.sizes[0];
+8
source

Source: https://habr.com/ru/post/1776428/


All Articles