Florent
Florent

Reputation: 1928

How to declare a variable when it's value is an object composed with a variable in JS?

I have several objects in a JSON formatted file with same string but different values :

{
    "object_1": {
        "data1": [1, -1],
        "data2": [2, -1],
        "data3": [3, -1],
    },
    "object_2": {
        "data1": [4, -1]
        "data2": [5, -1],
        "data3": [6, -1],
    }
}

I'm able to retrieve the data in the objects with getJSON() :

var url = "https://website.com/file.json";
$.getJSON(url, function (json) {
    var mydata1 = json.object_1.data1; 
    var mydata2 = json.object_1.data2; 
    var mydata3 = json.object_1.data3; 
});

But I have several objects and I don't want to duplicate the same three lines for all of them. I would like to create these variables mydata1 mydata2 and mydata3 by using a function with the object id as an input.

My problem is that I cannot figure out how to create a variable when it's value is an object composed with a variable. For example here id is a variable used to select the JSON objet : object_1 or object_2.

$.getJSON(url, function (json) {

    var id = 1 // use id = 1 on page load

    function loadJSON(id) {

        // all these declaration fail
        eval("var mydata1 = string.concat('json.object_', id, '.data1')"); 
        var mydata1 = string.concat("json.object_", id, ".data1");  
        var mydata1 = window["json.object_" + id + ".data1"];
    );

    // then rewrite the data on click

    $('#button_2').click(function () { 
        loadJSON(2);    
    });     
    $('#button_1').click(function () {    
        loadJSON(1);    
    });

)},

How can I declare these variables in a function ?

Thank you,

Upvotes: 1

Views: 43

Answers (1)

dfsq
dfsq

Reputation: 193261

Use bracket notation to reference value by variable property name:

var mydata1 = json['object_' + id].data1;

Upvotes: 1

Related Questions