Knockout JS可观测阵列数据组每个部分的总年龄计数 [英] Knockout JS Observable array data group total age count per section

查看:102
本文介绍了Knockout JS可观测阵列数据组每个部分的总年龄计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可观察数组

  var myArray = ko.observableArray([
{name:Jimmy ,输入:朋友,年龄:30},
{姓名:乔治,类型:朋友,年龄:40},
{姓名:Zippy ,年龄:20}
]);

现在我要输出为

朋友总人数:70



<吉米30
乔治40


敌人总计年龄:20 h2>

Zippy 20



有一个类似的jsfiddle link 解决方案

如果您想保留泛型结构(不只是直接为FriendTotalAge和EnemyTotalAge创建计算结果),那么您可以扩展 distinct 扩展以包含一个用于总数的属性。



例如,您可以传递要用作总计的属性的名称,并在扩展中添加一个部分,如:


$ b ($)$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $' key] .total = ko.computed(function(){
va r total = 0;
ko.utils.arrayForEach(propIndex [key],function(item){
total + = parseInt(ko.utils.unwrapObservable(item [totalProp]),10)|| 0;
});

总回报;
});
}
}
}

现在,您的索引可能会按类型并包含年龄属性的计算总和。

更新小提琴: http:// jsfiddle .net / rniemeyer / yrh5D /


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

解决方案

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/

这篇关于Knockout JS可观测阵列数据组每个部分的总年龄计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆