的價值我有對象的JavaScript數組,像這樣:JavaScript的 - 增加了兒童
[{
name: "Root 1",
countCases: 0,
children: [
{
name: "Root 1.1",
countCases: 3
},
{
name: "Root 1.2",
countCases: 1,
children: [
{
name: "Root 1.2.1",
countCases: 3
},
{
name: "Root 1.2.2",
countCases: 1
},
{
name: "Root 1.2.3",
countCases: 1
}
]
}
]
},
{
name: "Root 2",
countCases: 0,
children: [
{
name: "Root 2.1",
countCases: 3
},
{
name: "Root 2.2",
countCases: 0,
children: [
{
name: "Root 2.2.1",
countCases: 3
},
{
name: "Root 2.2.2",
countCases: 1
}
]
}
]
}]
我想加起來所有嵌套的孩子「countCases」的價值。對於這些值是:
Root 1 - 9
Root 1.1 - 3
Root 1.2 - 6
Root 1.2.1 - 3
Root 1.2.2 - 1
Root 1.2.3 - 1
Root 2 - 7
Root 2.1 - 3
Root 2.2 - 4
Root 2.2.1 - 3
Root 2.2.2 - 1
所以每個家長都有他們的「countCases」並添加了他所有孩子的「countCases」。預先感謝您的幫助。
@edit:我想是這樣的,但它不是工作:
function addCountCasesToParentFromChildren(data)
{
var sumCountCases = 0;
$.each(data, function(key, value) {
sumCountCases = value.countCases;
if (value.children != '')
{
value.countCases += addCountCasesToParentFromChildren(value.children);
}
});
return sumCountCases;
}
@ EDIT2:好的,我做到了。這是解決方案:
function addCountCasesToParentFromChildren(data)
{
var sumCountCases = 0;
$.each(data, function(key, value) {
if (value.children != '')
{
value.countCases += addCountCasesToParentFromChildren(value.children);
}
sumCountCases += value.countCases;
});
return sumCountCases;
}
只是一個遞歸遍歷的問題。你嘗試過什麼嗎? – Leo
我試過這樣的: function addCountCasesToParentFromChildren(data) { var sumCountCases = 0; $。每個(數據,功能(鍵,值){ sumCountCases = value.countCases; 如果(value.children = '') { value.countCases + = addCountCasesToParentFromChildren(value.children);! } }); return sumCountCases; } – JakubKubera
您的數組表示法不是JavaScript('=>'表示JavaScript中的其他內容,並且數組索引從0開始,而不是1)。 – trincot