Search code examples
javascriptrecursionlodash

Parent value as sum of all children values within nested javascript object


I have a deeply nested javascript object with an unlimited amout of children. Every child has a value and a totalValue. The totalValue should be the sum of all the values from all its children and subchildren. How can I make this work?

At the moment I'm only able to loop the whole object using a recursive function:

// Recursive function
_.each(names, function(parent) { 
    if(parent.children.length > 0) { 
        recursiveFunction(parent.children);
    }
});

function recursiveFunction(children){ 
    _.each(children, function(child) { 
        if(child.children.length > 0) { 
            recursiveFunction(child.children)
        }
    });
}; 

// Deeply nested javascript object
var names = {
    name: 'name-1',
    value: 10,
    valueTotal: 0, // should be 60 (name-1.1 + name-1.2 + name-1.2.1 + name-1.2.2 + name-1.2.2.1 + name-1.2.2.2)
    children: [{
            name: 'name-1.1',
            value: 10,
            valueTotal: 0,
            children: []
        }, {
            name: 'name-1.2',
            value: 10,
            valueTotal: 0, // should be 40 (name-1.2.1 + name-1.2.2 + name-1.2.2.1 + name-1.2.2.2)
            children: [{
                name: 'name-1.2.1',
                value: 10,
                valueTotal: 0,
                children: []
            }, {
                name: 'name-1.2.2',
                value: 10,
                valueTotal: 0, // should be 20 (name-1.2.2.1 + name-1.2.2.2)
                children: [{
                    name: 'name-1.2.2.1',
                    value: 10,
                    valueTotal: 0,
                    children: []
                }, {
                    name: 'name-1.2.2.2',
                    value: 10,
                    valueTotal: 0,
                    children: []
                }]
            }]
        }]
    }
}

Solution

  • So in fact you wanna do sth like this: every elem asks his childs for its values, these do the same and give back their totalValues plus their own value.

    function sumUp(object){
      object.totalValue = 0;
      for(child of object.children){
        object.totalValue += sumUp(child);
       }
       return object.totalValue + object.value;
    }
    

    Start like this:

    const totalofall = sumUp(names);
    console.log(names); //your expected result.
    

    Working example: http://jsbin.com/laxiveyoki/edit?console