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'
}
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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With