Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if an Object has children in JavaScript

In JavaScript you can get the children of an XML node like this...

var children = xml.childeNodes;

How do I get the children of an object?

var obj = {
  prop1: 'stuff',
  prop2: 'things',
  prop3: 'stuff-n-things'
}

Round two

Given an object like so..

var Obj = {
  levelOneProp1: 'stuff',
  levelOneProp2: 'things',
  levelOneProp3: {
     levelTwoProp1: 'moreStuff',
     levelTwoProp2: 'morethings',
     levelTwoProp3: 'morestuff-n-things'
  } 
}

I would like to know which properties in Obj have children so I can loop through them in a recursive manner. The goal is to be able to supply a dataset with an (theoretically) unlimited number of children and apply their values to input elements... Here is what I have so far.

function applyData( dataSet ){
    var hasChildren = false;

    for(var i = 0; i < dataSet.childNodeArrayGoesHere.length; i++){
        if(dataSet.detectChildNodesHere){
            hasChildren = true;
        }
    }

    if(hasChildren){
        for(var j = 0; j < dataSet.childNodeArrayGoesHere.length; i++){
            applyData(dataSet[j]);
        }
    } else {
        //apply the key/value pair to an input element

        $("input[name" + dataSet.propertyName + "]").val(dataSet.propertyValue);
    }
}
like image 444
Derek Adair Avatar asked May 04 '11 17:05

Derek Adair


1 Answers

You can iterate over all properties of an object like this:

var o = { prop1: 'this is prop 1', prop2: 'this is prop2'};

for(var propName in o) {
    if(o.hasOwnProperty(propName)) {
        alert(o[propName]);   
    }
}

The hasOwnProperty() function checks to make sure that the specified property actually exists in the object. Using it in this context makes sure you don't get any inherited properties.

like image 135
Mark Biek Avatar answered Sep 25 '22 19:09

Mark Biek