Recursive iteration over dynamically nested object array

后端 未结 2 1731
广开言路
广开言路 2020-12-29 15:50

I am using angular JS and one of their examples:http://jsfiddle.net/furf/EJGHX/

I need to take the data when the update function occurs and add some values to it bef

相关标签:
2条回答
  • 2020-12-29 16:28

    If I'm understanding you correctly, you want each 'child' to have a parentID (defined by its parent; 0 otherwise) and an index (based on its position within it sibling set).

    function normalize(parent) {
        if (parent && parent.children) {
            for (var i = 0, l = parent.children.length; i < l; ++i) {
                var child = parent.children[i];
                child.index = i;
                if (!child.parentId) child.parentId = parent.id || '0';
                normalize(child);
            }
        }
    }
    
    normalize(data);
    
    0 讨论(0)
  • 2020-12-29 16:38

    Recursion is calling function inside the same function. Your sample is not a recursion at all;

    function runRecursive(input) {
        for (var i = 0, l = input.length; i < l; i++) {
            var current = input[i];
    
            parentid = current.id == null ? '0' : current.id;
            current.index = i;
            if (current.children && current.children.length > 0) {
                runRecursive(current.children);
            };
        };
    };
    
    runRecursive(data.children);
    

    Also you should define i and l with var keyword, otherwise it will be located in window context and recursion logic will broken. Though I don't get what is parentid variable for and why it defined outside visible code.

    0 讨论(0)
提交回复
热议问题