Reputation: 115
I have a grid with rows and columns. I also have an additional column that keeps track of the totals. I have a JSON data similar to this:
{
GreatGrandfather: {
GrandFather: {
Father: [
{
Son: [
{
Name: "A",
Cost: "100"
},
{
Name: "B",
Cost: "1",
},
{
Name: "C",
Cost: "50",
}
]
},
{
[
Son: {
{
Name: "A",
Cost: "44"
},
{
Name: "B",
Cost: "13",
},
{
Name: "C",
Cost: "22",
}
]
}
]
}
}
}
I can I have a dynamic number of fathers and sons. My question is how do I display the sums of sons by name? So for this example, I would have 3 totals. Sum of A (144), B (14) and C(72). Please help! Thanks
Upvotes: 0
Views: 120
Reputation: 7342
Organizing you data the way you have it, is hard to do. What you are asking to do is much easier to do server side.
If you reorganize data so that you want sum the costs for each Son, that is doable because you can do it with for loops. I have a working demo of that at http://jsfiddle.net/photo_tom/p6dW6/15/.
I added the following ko.computed to each of the Son array object.
var sons = vm.GreatGrandfather.GrandFather.Father();
var i = sons.length;
for (var i1 = 0; i1 < i; i1++) {
sons[i1].sum = ko.computed({
read: function() {
var sonsArray = this.Son();
var sonsLen = sonsArray.length;
var sum = 0;
for (var i2 = 0; i2 < sonsLen; i2++) {
var costValue = sonsArray[i2].Cost();
sum += Number(costValue) ;
}
return sum;
},
owner: sons[i1]
});
Upvotes: 1