3

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

Chand Priyankara
  • 6,739
  • 2
  • 40
  • 63
Nicholas Mordecai
  • 859
  • 2
  • 12
  • 33

1 Answers1

3

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);
);
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339