JQuery JSON push using object as key

I am trying to write a JSON file using JQuery. I am trying to use a javascript object as a json key, however it won't run. My code:

var lvl = 2;
$.getJSON( "json/levels.json", function(levels) {
    levels.level.push({
        lvl:[{
            "Test": "some text"
        }] 
    }
);

      

Output:

{
    "level": [{
        "lvl": [{
            "Test": "Some Text",
        }]
    }]
}

      

However, it should return:

{
    "level": [{
        "2": [{
            "Test": "Some Text",
        }]
    }]
}

      

What am I doing wrong?

Thanks Nick

+3


source to share


1 answer


To use the value of a variable as the key of an object, try this:



$.getJSON( "json/levels.json", function(levels) {
    var obj = {};
    obj[lvl] = [{ "Test": "some text" }];
    levels.level.push(obj);
);

      

+3


source







All Articles