2

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

2 Answers 2

1

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

6 Comments

That's not working for some reason. I tested your code exactly as it is written.
Added another line please retry
answers need to be in an object first: jsfiddle.net/mplungjan/EVsM2 var dataObj = { "first_name":{ "answers":["John"] } }
It works. Thanks. What if I wanted to assign the value using JSON instead of a Javascript array (like in the second example I gave above)? Is that possible?
Thanks mplungjan. I think I understand.
|
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]);​​​​​​​​​​​​​

1 Comment

var data = new Array() should be var data = {} and data[field_name] = new Array(); should be data[field_name] = {} and data[field_name]['answers'] = new Array(); should be data[field_name]['answers'] = [];

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.