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!

pmerino
  • 5,900
  • 11
  • 57
  • 76
  • possible duplicate of [Passing in dynamic key:value pairs to an object literal?](http://stackoverflow.com/questions/4119324/passing-in-dynamic-keyvalue-pairs-to-an-object-literal) – Felix Kling Jan 05 '12 at 13:29

4 Answers4

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);
Dennis
  • 32,200
  • 11
  • 64
  • 79
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);
jabclab
  • 14,786
  • 5
  • 54
  • 51
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);
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • @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.) – nnnnnn Jan 05 '12 at 14:00
  • The Unicode bit sounds familiar - I keep forgetting `"this"` and `["t", "h", "i", "s"]` are valid JSON. – Dennis Jan 05 '12 at 14:18
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":""}.

einPaule
  • 121
  • 1
  • 5