【问题标题】:Count property values of javascript object计算 javascript 对象的属性值
【发布时间】:2013-07-12 12:52:24
【问题描述】:

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

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"
}
]

【问题讨论】:

    标签: json object properties count


    【解决方案1】:

    如何根据月份值创建地图,如下所示:

    //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]);
        }
    }
    

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

    //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...
    

    【讨论】:

    • 很高兴为您提供帮助!如果您有机会将此答案标记为已接受,我将不胜感激。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-01-03
    • 2022-01-10
    • 2021-01-02
    • 2017-06-07
    • 2015-09-20
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多