Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: data.push is not a function

I am trying to push

data.push({"country": "IN"}); 

as new id and value to a json string. but it gives the following error

Uncaught TypeError: data.push is not a function  data{"name":"ananta","age":"15"} 

Advance Thanks for your reply

like image 237
Ananta Prasad Avatar asked Apr 17 '15 10:04

Ananta Prasad


People also ask

Is not a function at Push?

The "push is not a function" error occurs when the push() method is called on a value that is not an array. To solve the error, convert the value to an array before calling the method, or make sure to only call the push() method on valid arrays. Here is an example of how the error occurs.

Is not a function TypeError?

A TypeError: "x" is not a function occurs when a function is called on an object that does not contain the called function. When calling a built-in function that expects a callback function argument, which does not exist. When the called function is within a scope that is not accessible.

How does push work in Javascript?

push() The push() method adds one or more elements to the end of an array and returns the new length of the array.


1 Answers

To use the push function of an Array your var needs to be an Array.

Change data{"name":"ananta","age":"15"} to following:

var data = [     {          "name": "ananta",         "age": "15",         "country": "Atlanta"     } ];  data.push({"name": "Tony Montana", "age": "99"});  data.push({"country": "IN"});  .. 

The containing Array Items will be typeof Object and you can do following:

var text = "You are " + data[0]->age + " old and come from " + data[0]->country;

Notice: Try to be consistent. In my example, one array contained object properties name and age while the other only contains country. If I iterate this with for or forEach then I can't always check for one property, because my example contains Items that changing.

Perfect would be: data.push({ "name": "Max", "age": "5", "country": "Anywhere" } );

So you can iterate and always can get the properties, even if they are empty, null or undefined.

edit

Cool stuff to know:

var array = new Array(); 

is similar to:

var array = []; 

Also:

var object = new Object(); 

is similar to:

var object = {}; 

You also can combine them:

var objectArray = [{}, {}, {}]; 
like image 182
Cagatay Ulubay Avatar answered Oct 08 '22 15:10

Cagatay Ulubay