Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a JSON array key on array.push on JavaScript

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!

like image 754
pmerino Avatar asked Jan 18 '23 21:01

pmerino


2 Answers

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);
like image 116
Dennis Avatar answered Jan 29 '23 06:01

Dennis


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);
like image 37
jabclab Avatar answered Jan 29 '23 04:01

jabclab