How to set JSON array key to array.push in JavaScript

I am doing 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 I do this code, the part where I just write the test variable, it just becomes the "test" key, so I have no idea to get this for wok. How could this happen? Thanks!

+4
source share
4 answers

If you need variables as keys, you need parentheses:

 var object = {}; object['dd'+questNumb] = {"title":""}; object["content"] = {"date":""}; //Or object.content, but I used brackets for consistency window.voiceTestJSON.push(object); 
+4
source

You will 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); 
+2
source

(First, you do not have a JSON array, you have a JavaScript object. JSON is a string representation of data with a syntax that looks like the syntax of a JavaScript object literal.)

Unfortunately, when you use an XML literal object to create an object, you cannot use variables to set dynamic property names. First you need to create an object, and then add the properties using the syntax obj[propName] :

 var test = "dd" + questNumb, myObj = { "content" : {"date":""} }; myObj[test] = {"title" : ""}; window.voiceTestJSON.push(myObj); 
+2
source
 {test:{"title":""}, "content":{"date":""}} 

This is a JS object. So you are calling the object in the voiceTestJSON array.

Unlike JSON, JS Object names can be written with or without quotation marks.

What you want to do can be achieved as follows:

 var test = 'dd'+questNumb; var newObject = {"content":{"date":""}}; //this part does not need a variable property name newObject[test] = {"title":""}; 

Thus, you set the property with the name contained in the test to {"title": ""}.

0
source

Source: https://habr.com/ru/post/1389467/


All Articles