Stephen305
Stephen305

Reputation: 1097

How to assign values to JSON object

I have the following code that does not work. I am trying to push the text "John" onto the end of the object. I am more familiar with PHP, and this works in PHP.

var data = {};
var field_name = "first_name";

data[field_name]['answers'][] = "John";

alert(data['first_name']['answers'][0]);

Edit:

I also tried the following and it did not work.

var data = {};
var field_name = "first_name";
var i=0;

data[field_name]['answers'][i] = "John";

alert(data['first_name']['answers'][0]);

Upvotes: 2

Views: 3784

Answers (2)

BraedenP
BraedenP

Reputation: 7215

One can't arbitrarily define more array dimensions or dynamically extend bounds like PHP will happily allow. You'll need to do something like this (the shorthand [ ] notation can also be used in place of new Array(). I just prefer this way.):

var data = {};
var field_name = "first_name";

//Create the new dimensions
data[field_name] = new Array();
data[field_name]['answers'] = new Array();
//Push the new element
data[field_name]['answers'].push("John");

alert(data['first_name']['answers'][0]);​​​​​​​​​​​​​

Upvotes: 0

Daniel Elliott
Daniel Elliott

Reputation: 22867

try this:

var data = {};
var field_name = "first_name";
data[field_name] = {};
data[field_name].answers = [];
data[field_name].answers.push("John");

alert(data['first_name'].answers[0]);

Upvotes: 1

Related Questions