问题
I have an observable array
var myArray = ko.observableArray([
{ name: "Jimmy", type: "Friend", Age: 30 },
{ name: "George", type: "Friend", Age: 40 },
{ name: "Zippy", type: "Enemy", Age: 20 }
]);
Now I want my output as
Friend Total Age: 70
Jimmy 30 George 40
Enemy Total Age : 20
Zippy 20
There is a similar jsfiddle link
回答1:
If you want to keep with the generic structure (not just create computeds directly for "FriendTotalAge" and "EnemyTotalAge"), then you could expand the distinct
extension to include a property to use for the total.
For example, you could pass in the name of the property that you want to use as a total and add a section in the extension like:
if (totalProp) {
for (key in propIndex) {
if (propIndex.hasOwnProperty(key)) {
propIndex[key].total = ko.computed(function() {
var total = 0;
ko.utils.arrayForEach(propIndex[key], function(item) {
total += parseInt(ko.utils.unwrapObservable(item[totalProp]), 10) || 0;
});
return total;
});
}
}
}
Now, your index could be by "type" and contain a computed total of the "age" property.
Update of the fiddle here: http://jsfiddle.net/rniemeyer/yrh5D/
来源:https://stackoverflow.com/questions/13897411/knockout-js-observable-array-data-group-total-age-count-per-section