子供の数に制限のない深くネストされたjavascriptオブジェクトがあります。すべての子は値とtotalValueを持っています。 totalValueは、すべての子と子要素のすべての値の合計でなければなりません。どうすればこの作品を作れますか?再帰関数を使用して、私は唯一のループすることができるよ瞬間、オブジェクト全体でネストされたjavascriptオブジェクト内のすべての子の値の合計としての親の値
:
// 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: []
}]
}]
}]
}
}
あなたの合計が間違って見え、名前-2は、名前-1の子であり、含まれるべきです。 –
あなたの権利!私はそれを変更します。 – Sam