Why is JSONObject.length undefined?

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, the JSONObject.length code JSONObject.length is undefined. Why?

 var JSONObject = { "name": "John Johnson", "street": "Oslo West 16", "age": 33, "phone": "555 1234567" }; 
+7
json javascript
source share
2 answers

JavaScript does not have a .length property for objects. If you want to do this, you will have to manually iterate over 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 switched over as it was originally written, IE8 doesn't matter, so you should feel safe when using Object.keys(JSONObject).length . Much cleaner.

+14
source share

The following is 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" }]; 

Thus, the length of JavaScript is a property of the 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. Therefore, the length property is not available and will be undefined. Therefore, you can do 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 an object, say JSONObject . You can try the following:

 var JSONObject = {"name":"John Johnson", "street":"Oslo West 16", "age":33, "phone":"555 1234567"}; var jsonObjArray = []; // = new Array(); jsonObjArray.push(JSONObject); 

And you will get the length property.

+3
source share

All Articles