I am trying to push
data.push({\"country\": \"IN\"});
as new id and value to a json string. but it gives the following error
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 = [{}, {}, {}];
one things to remember push work only with array[] not object{}.
if you want to add Like object o inside inside n