mheavers
mheavers

Reputation: 30158

javascript how to find number of children in an object

is there a way to find the number of children in a javascript object other than running a loop and using a counter? I can leverage jquery if it will help. I am doing this:

var childScenesObj = [];
var childScenesLen = scenes[sceneID].length; //need to find number of children of scenes[sceneID]. This obviously does not work, as it an object, not an array.


for (childIndex in scenes[sceneID].children) {
    childSceneObj = new Object();
    childSceneID = scenes[sceneID].children[childIndex];
    childSceneNode = scenes[childSceneID];
    childSceneObj.name = childSceneNode.name;
    childSceneObj.id = childSceneID;
    childScenesObj  .push(childSceneObj);
}

Upvotes: 14

Views: 26231

Answers (2)

Brian
Brian

Reputation: 2778

If that object is actually an Array, .length will always get you the number of indexes. If you're referring to an object and you want to get the number of attributes/keys in the object, there's no way I know to that other than a counter:

var myArr = [];
alert(myArr.length);// 0
myArr.push('hi');
alert(myArr.length);// 1

var myObj = {};
myObj["color1"] = "red";
myObj["color2"] = "blue";

// only way I know of to get "myObj.length"
var myObjLen = 0;
for(var key in myObj)
  myObjLen++;

Upvotes: 0

Eliu
Eliu

Reputation: 767

The following works in ECMAScript5 (Javascript 1.85)

var x = {"1":1, "A":2};
Object.keys(x).length; //outputs 2

Upvotes: 44

Related Questions