I'm trying to build a tree using JSON for which i'm trying to just print in browser console.
var json = [{
name: "1",
id: 1,
child: [{
name: "11",
id: 11,
child: [{
name: "111",
id: 111
}, {
name: "112",
id: 112
}]
}, {
name: "12",
id: 12
}]
}];
function ya(obj) {
console.log(obj.name);
if (obj.child) {
console.log("length=" + obj.child.length);
for (i = 0; i < obj.child.length; i++) {
ya(obj.child[i]);
}
}
}
ya(JSON.parse(JSON.stringify(json))[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here I would like to print
1
11
111
112
12
in console. But it only prints
1
11
111
112
I want to do this recursively. How can I achieve this?