4

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!

1

4 Answers 4

5

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

2

(First of all, you don't have a JSON array, you have a JavaScript object. JSON is a string representation of data with a syntax that looks like JavaScript's object literal syntax.)

Unfortunately when you use JavaScript's object literal syntax to create an object you can not use variables to set dynamic property names. You have to create the object first and then add the properties using the obj[propName] syntax:

var test = "dd" + questNumb,
    myObj = { "content" : {"date":""} };

myObj[test] = {"title" : ""};

window.voiceTestJSON.push(myObj);

2 Comments

@Dennis - yes, "subset" is the word typically used, though strictly speaking it is not quite right given that "[1,2,3]" is valid JSON but is array literal notation rather than object literal notation. (Also I believe there are some unicode characters that are valid in JSON but not in JavaScript, though for the life of me I can't remember the details and I can't be bothered looking it up.)
The Unicode bit sounds familiar - I keep forgetting "this" and ["t", "h", "i", "s"] are valid JSON.
0
{test:{"title":""}, "content":{"date":""}}

this is a JS object. So you are pushing an object into the voiceTestJSON array.

Unlike within JSON, JS Object property names can be written with or without quotes.

What you want to do can be achieved like this:

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

This way you are setting the property with the name contained in test to {"title":""}.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.