Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 248
mheavers Avatar asked Aug 16 '11 15:08

mheavers


People also ask

How do you count child nodes?

Use the getChildCount() method in Java to get the count of child nosed of any node i.e. even if it's a root node or not.

How do you count the number of keys in an object?

keys() method and the length property are used to count the number of keys in an object. The Object. keys() method returns an array of a given object's own enumerable property names i.e. ["name", "age", "hobbies"] . The length property returns the length of the array.


1 Answers

The following works in ECMAScript5 (Javascript 1.85)

var x = {"1":1, "A":2};
Object.keys(x).length; //outputs 2
like image 175
Eliu Avatar answered Oct 11 '22 14:10

Eliu