Reputation: 2240
I am trying to list out all the elements inside an array and as you can see Company has three levels, but I've only written the script to print the output until two levels. How do I access the third level? What should be the array that I should be using inside the third for loop
?
Upvotes: 0
Views: 653
Reputation: 645
What you're looking for is recursion.
Here is a fixed version of your fiddle: http://jsfiddle.net/jEmf9/
function generateEntity(obj) {
var html = [];
var name = obj.entity;
html.push('<li>');
html.push(name);
html.push('</li>');
var arrayName = name.replace(/\s/gi, '_');
if (obj[arrayName] == undefined) {
return html.join('');
}
var entity = obj[arrayName];
for (var i = 0; i < entity.length; i++) {
html.push('<ul>');
html.push(generateEntity(entity[i]));
html.push('</ul>');
}
return html.join('');
}
Upvotes: 2
Reputation: 88418
In your case you do not need a special technique for accessing the third level. You need to write a recursive tree walking function so that you can render a tree of any depth.
I've done a quick patch of your code here: http://jsfiddle.net/rtoal/xcEa9/6/
Once you get things working as you like, you can work on forming your html. Your repeated string concatenation using +=
is known to be extremely inefficient, but that is outside the scope of this question. :)
Upvotes: 0