父值作为嵌套 javascript 对象中所有子值的总和

Sam*_*Sam 2 javascript recursion lodash

我有一个深度嵌套的 javascript 对象,其中包含无限数量的孩子。每个孩子都有一个值和一个 totalValue。totalValue 应该是其所有孩子和子孩子的所有值的总和。我怎样才能使这项工作?

目前我只能使用递归函数循环整个对象:

// 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: []
                }]
            }]
        }]
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*lms 5

所以事实上你想做这样的事情:每个 elem 都会向他的孩子询问它的值,这些都做同样的事情并返回他们的 totalValues 加上他们自己的价值。

function sumUp(object){
  object.totalValue = 0;
  for(child of object.children){
    object.totalValue += sumUp(child);
   }
   return object.totalValue + object.value;
}
Run Code Online (Sandbox Code Playgroud)

这样开始:

const totalofall = sumUp(names);
console.log(names); //your expected result.
Run Code Online (Sandbox Code Playgroud)

工作示例:http : //jsbin.com/laxiveyoki/edit?console