Knockout JS Observable array data group total age count per section

半世苍凉 提交于 2019-12-10 11:49:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!