简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM