计算javascript对象的属性值 [英] Count property values of javascript object

查看:80
本文介绍了计算javascript对象的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个javascript对象,我是通过json从数据库中获取的。有什么简单的方法可以计算基于同一个月的值? (颜色并不重要)。因此结果将是这样的:

I have an javascript object, which I´m getting from database via json. Is there any easy way how to count values based on the same month? (color isn´t important). So the results will be something like this:

data = [
{
    "value": 30,
    "month": 8,
    "color": "#49e630"
},
{
    "value": 50,
    "month": 7,
    "color": "#5001dc"
},
{
    "value": 100,
    "month": 7,
    "color": "#6365c3"
}
]

result = [
{
    "value": 30,
    "month": 8,
    "color": "#49e630"
},
{
    "value": 150,
    "month": 7,
    "color": "#6365c3"
}
]


推荐答案

如何根据月份值创建地图,像这样:

How about creating a map based on the month value, like so:

//populate a map with keys based on the month
var monthMap = new Object();
for (var i = 0; i < data.length; i++) {
    if (monthMap[data[i]['month']] == null) {
        monthMap[data[i]['month']] = data[i];
    } else {
        monthMap[data[i]['month']]['value'] += data[i]['value'];
    }
}

//convert monthMap to list
var result = [];
for (var key in monthMap) {
    if (monthMap.hasOwnProperty(key)) {
        result.push(monthMap[key]);
    }
}

编辑:您也可以这样编写数据循环,这可能会更清晰一些:

you could also write the data loop like this, which may be slightly more legible:

//populate a map with keys based on the month
var monthMap = new Object();
data.forEach(function(listitem) {

    var month = listitem['month'];

    if (monthMap[month] == null) {
        monthMap[month] = listitem;
    } else {
        monthMap[month]['value'] += listitem['value'];
    }
});

//convert to list...

这篇关于计算javascript对象的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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