Sum javascript object propertyA values with same object propertyB in array of objects

前端 未结 9 2609
醉梦人生
醉梦人生 2020-11-22 04:48

How would one take a javascript array of objects such as:

my objArr = [
{key:Mon Sep 23 2013 00:00:00 GMT-0400, val:42},
{key:Mon Sep 24 2013 00:00:00 GMT-04         


        
9条回答
  •  自闭症患者
    2020-11-22 05:39

    you can also try using javascript linq framework which is exactly same as sql statement which is given desired output with less written code and effective and found at linq.js

    var objArr = 
    [
    {key:'Mon Sep 23 2013 00:00:00 GMT-0400', val:42},
    {key:'Mon Sep 24 2013 00:00:00 GMT-0400', val:78},
    {key:'Mon Sep 25 2013 00:00:00 GMT-0400', val:23},
    {key:'Mon Sep 23 2013 00:00:00 GMT-0400', val:54}
    ];
    
    
    var aggregatedObject = Enumerable.From(objArr)
            .GroupBy("$.key", null,
                     function (key, g) {
                         return {
                           key: key,
                           contributions: g.Sum("$.val")
                         }
            })
            .ToArray();
    
    console.log(aggregatedObject);

    which is pretty easy as compare to looping. i hope this may help.

提交回复
热议问题