Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is JSONObject.length undefined? [closed]

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"
};
like image 310
user2672420 Avatar asked Sep 26 '13 15:09

user2672420


2 Answers

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.

like image 143
Doug Avatar answered Sep 20 '22 13:09

Doug


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.

like image 37
Amol M Kulkarni Avatar answered Sep 21 '22 13:09

Amol M Kulkarni