Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery JSON push using object as key [duplicate]

I am trying to write a JSON file using JQuery. I am attempting to use a javascript object as a json key however it does not run. My code is:

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

This outputs:

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

However, it should be returning:

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

What am I doing wrong?

Thanks Nick

like image 900
Nicholas Mordecai Avatar asked Jul 11 '26 19:07

Nicholas Mordecai


1 Answers

To use the value of the 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);
);
like image 70
Rory McCrossan Avatar answered Jul 13 '26 12:07

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!