In the code below, JSONObject.length
is 2:
var JSONObject = [{
"name": "John Johnson",
"street": "Oslo West 16",
"age": 33,
"phone": "555 1234567"
}, {
"name": "John Johnson",
"street": "Oslo West 16",
"age": 33,
"phone": "555 1234567"
}];
However, in the code below, JSONObject.length
is undefined. Why?
var JSONObject = {
"name": "John Johnson",
"street": "Oslo West 16",
"age": 33,
"phone": "555 1234567"
};
JavaScript doesn't have a .length property for objects. If you want to work it out, you have to manually iterate through the object.
function objLength(obj){
var i=0;
for (var x in obj){
if(obj.hasOwnProperty(x)){
i++;
}
}
return i;
}
alert(objLength(JSONObject)); //returns 4
Edit:
Javascript has moved on since this was originally written, IE8 is irrelevant enough that you should feel safe in using Object.keys(JSONObject).length
instead. Much cleaner.
The following is actually an array of JSON objects :
var JSONObject = [{ "name":"John Johnson", "street":"Oslo West 16", "age":33,
"phone":"555 1234567"}, {"name":"John Johnson", "street":"Oslo West 16",
"age":33, "phone":"555 1234567" }];
So, in JavaScript length is a property of an array. And in your second case i.e.
var JSONObject = {"name":"John Johnson", "street":"Oslo West 16", "age":33,
"phone":"555 1234567"};
the JSON object is not an array. So the length property is not available and will be undefined. So you can make it as an array as follows:
var JSONObject = [{"name":"John Johnson", "street":"Oslo West 16", "age":33,
"phone":"555 1234567"}];
Or if you already have object say JSONObject
. You can try following:
var JSONObject = {"name":"John Johnson", "street":"Oslo West 16", "age":33,
"phone":"555 1234567"};
var jsonObjArray = []; // = new Array();
jsonObjArray.push(JSONObject);
And you do get length
property.
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