Javascript根据条件减少到组对象

标签 javascript

我有以下数据:

var foo = [
    {'MonthNo' : 03, 'CustomerTypeID' : 1 , 'TotalSales' : 45 },
    {'MonthNo' : 03, 'CustomerTypeID' : 2 , 'TotalSales' : 64 },
    {'MonthNo' : 03, 'CustomerTypeID' : 4 , 'TotalSales' : 89 },
    {'MonthNo' : 03, 'CustomerTypeID' : 5 , 'TotalSales' : 42 },
    {'MonthNo' : 04, 'CustomerTypeID' : 1 , 'TotalSales' : 66 },
    {'MonthNo' : 04, 'CustomerTypeID' : 2 , 'TotalSales' : 78 },
    {'MonthNo' : 04, 'CustomerTypeID' : 5 , 'TotalSales' : 20 },
    {'MonthNo' : 04, 'CustomerTypeID' : 6 , 'TotalSales' : 10 }
];

我想把这个转换成下面的

{'MonthNo' : 03, 'CustomerTypeID' : 1 , 'TotalSales' : 198 },
{'MonthNo' : 03, 'CustomerTypeID' : 5 , 'TotalSales' : 42 },
{'MonthNo' : 04, 'CustomerTypeID' : 1 , 'TotalSales' : 144 },
{'MonthNo' : 04, 'CustomerTypeID' : 5 , 'TotalSales' : 20 },
{'MonthNo' : 04, 'CustomerTypeID' : 6 , 'TotalSales' : 10 }

对于每个 MonthNo,除了 CustomerTypeID 5 和 6 之外,我想将 TotalSales 值相加。 例如:CustomerTypeID 1、2、4 的 MonthNo 03,它们的 TotalSales 值总和为 198。类似地,对于 MonthNo 04,CustomerTypeID 1 和 2 的 TotalSales 值加起来为 144。

我试过使用reduce函数

var result = foo.reduce(function(obj,item){
    // code here
},{});

但是,我无法将它们分开以获得所需的结果。任何帮助将不胜感激。

最佳答案

您可以检查特殊情况并使用哈希表来引用正确的对象进行计数。

var foo = [{ MonthNo: '03', CustomerTypeID: 1, TotalSales: 45 }, { MonthNo: '03', CustomerTypeID: 2, TotalSales: 64 }, { MonthNo: '03', CustomerTypeID: 4, TotalSales: 89 }, { MonthNo: '03', CustomerTypeID: 5, TotalSales: 42 }, { MonthNo: '04', CustomerTypeID: 1, TotalSales: 66 }, { MonthNo: '04', CustomerTypeID: 2, TotalSales: 78 }, { MonthNo: '04', CustomerTypeID: 5, TotalSales: 20 }, { MonthNo: '04', CustomerTypeID: 6, TotalSales: 10 }],
    result = foo.reduce(function (hash) {
        return function (r, a) {
            var cType = [5, 6].indexOf(a.CustomerTypeID) === -1 ? 1 : a.CustomerTypeID,
                key = [a.MonthNo, cType].join('|');

            if (!hash[key]) {
                hash[key] = { MonthNo: a.MonthNo, CustomerTypeID: cType, TotalSales: 0 };
                r.push(hash[key]);
            }
            hash[key].TotalSales += a.TotalSales;
            return r;
        }
    }(Object.create(null)), []);
 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于Javascript根据条件减少到组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41236554/

相关文章:

javascript - 计算用户拖动鼠标的秒数

javascript - 在生产中使用 css/javascript source-maps 的性能影响?

javascript - jQuery 点击事件停止工作

javascript - 日期:ISO 8601 日期实例中的 getDate() 值错误

javascript - Java Nashhorn 换行

javascript - Ember.js 1.10 - 无法在 'setAttribute' : 'Element' ' is not a valid attribute name 上执行 '"

javascript - Android : Detect history. WebView 中的 back()

javascript - 全部展开或全部折叠

javascript - 手写笔:将样式添加到在 javascript 中生成的 id

javascript - 如何让我的 jQuery 插件尊重 end()?