I'm working on a function that is outputting a tree-like object with unknown depth.
This is what I have so far:
function recursive(obj) {
if ($.type(obj.children) == 'undefined') {
return "<ul><li>"+obj.name+"</li></ul>";
}
return "<ul><li>" +obj.name+"</li>" + recursive(obj.children) + "</ul>";
}
var x = recursive(obj1);
console.log(x);
This works well for objects that have no siblings, like this one:
var obj1 = {
name:'product 1',
children: {
name:'product 2',
children: {
name:'product 3'
}
}
}
It outputs:
- product 1
- product 2
- product 3
What I need is a recursive function (with a loop inside I guess) that is able to output arrays of objects too. The siblings basically.
Here's an example object and the output I'm trying to achieve:
var tree =
[{
name:'product 1'
}, {
name:'product 2',
children: [{
name:'product 3',
children: {
name:'product 4',
children: {
name:'product 5'
}
}
}, {
name:'product 6'
}, {
name:'product 7'
}]
}, {
name:'product 8'
}];
That should produce the following output:
- product 1
- product 2
- product 3
- product 4
- product 5
- product 6
- product 7
- product 8
Can anyone help? Thank you.