Is there are a way to recursively loop over all the nested properties of a JS/jQuery object?
For example, given this object
var x = {
'name': 'a',
'level': 1,
'children': [{
'name': 'b',
'level': 2,
'children': [{
'name': 'c',
'level': 3,
'children': [{
...
}]
}]},
...
}]
}
how could I loop over the objects named 'a' and their children, 'b' and their children, 'c' and their children, ad infinitum?
A recursive approach seems best, something like this:
function recursiveIteration(object) {
for (var property in object) {
if (object.hasOwnProperty(property)) {
if (typeof object[property] == "object"){
recursiveIteration(object[property]);
}else{
//found a property which is not an object, check for your conditions here
}
}
}
}
This is a working fiddle
Your JSON is not well formatted but you can "visit" each item as below:
<html>
<head>
<title>test</title>
<script type="text/javascript">
var x = {
"name": "a",
"level": 1,
"children": [
{
"name": "b",
"level": 2,
"children": [
{
"name": "c",
"level": 3,
"children": [
{
"sss": 23
}
]
}
]
}
]
};
function visit(obj){
for(var prop in obj){
if(typeof(obj[prop]) == 'object'){
if(Object.prototype.toString.call(obj[prop]) == '[object Array]'){
for(var i = 0; i < obj[prop].length; i++){
document.write("<br />the element " + prop + " (array) was visited");
visit(obj[prop][i]);
}
}else{
document.write("<br />the element " + prop + " (object) was visited");
visit(obj[prop]);
}
}else{
document.write("<br />the element " + prop + " = " + obj[prop] + " was visited");
}
}
}
visit(x);
</script>
</head>
<body>
</body>
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