I'm making some JS code, where I need to set a variable as a key in a JSON array with Javascript array.push():
var test = 'dd'+questNumb;
window.voiceTestJSON.push({test:{"title":""}, "content":{"date":""}});
Where questNumb is another variable. When doing that code, the part where I just write the test variable it just becomes to the key "test", so I have no idea of getting this to wok. How could it be? Thanks!
If you want variables as keys, you need brackets:
var object = {};
object['dd'+questNumb] = {"title":""};
object["content"] = {"date":""};  //Or object.content, but I used brackets for consistency
window.voiceTestJSON.push(object);
                        You'd need to do something like this:
var test = "dd" + questNumb,
    obj = {content: {date: ""}};
// Add the attribute under the key specified by the 'test' var
obj[test] = {title: ""};
// Put into the Array
window.voiceTestJSON.push(obj);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With