November 29, 201510 yr On my work i had the task to find values of nested objects. I solved it with recursion. I found this code in internet. Demo But our programmers said that it's not good to use recursion for that. Please, let me know if there is any other solution without recursion? I am very curious! var data = { "Рыбы": { "Форель": {}, "Щука": {} }, "Деревья": { "Хвойные": { "Лиственница": {}, "Ель": {} }, "Цветковые": { "Берёза": {}, "Тополь": {} } } }; function createTree(container, obj) { container.innerHTML = createTreeText(obj); } function createTreeText(obj) { // отдельная рекурсивная функция var li = ''; for (var key in obj) { li += '<li>' + key + createTreeText(obj[key]) + '</li>'; } if (li) { var ul = '<ul>' + li + '</ul>' } return ul || ''; } var container = document.getElementById('container'); createTree(container, data); Edited November 29, 201510 yr by fleur
November 29, 201510 yr Why is recursion bad? Recursion is ideal for tree like data structures - i.e. objects.
November 29, 201510 yr Author I didn't get actually.. but he said that recursion does to much request for site.. something like that. I closed my task in task manager but was said after his words. But if recursion is good i will continue use it in the future. Thank you for answer!
November 29, 201510 yr I didn't get actually.. but he said that recursion does to much request for site.. something like that. I closed my task in task manager but was said after his words. But if recursion is good i will continue use it in the future. Thank you for answer! Unless we're not getting the full story here you just have some JSON data, that's a single request you made... To move through it via recursion is pretty standard practice. Recursion isn't my strongpoint. I find it hard to follow when moving through complex tree structures, but this is where it is best suited. It IS slower than using a loop but we're talking microseconds here so that kind of optimisation isn't important. With recursion we get access to the call stack which is handy for debugging. Just be aware if you have a stupidly deep tree you could overflow the stack, but that's highly unlikely (And is fixed in ES6) Edited November 29, 201510 yr by rbrtsmith
November 29, 201510 yr Author Thank you! i didn't see the real issues after using recursion, indeed. So.. i think i will continue use recursion for this kind of task (common task for me on this work).
Create an account or sign in to comment