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
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.
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.
push() The push() method adds one or more elements to the end of an array and returns the new length of the array.
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 = [{}, {}, {}];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With