Recursive iteration over dynamically nested object array

后端 未结 2 1788
广开言路
广开言路 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);
    

提交回复
热议问题