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

前端 未结 9 2479
醉梦人生
醉梦人生 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:38

    Simpler reduce than posted elsewhere

    const 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}];
    
    const output = objArr.reduce((accumulator, cur) => {
      let date = cur.key;
      let found = accumulator.find(elem => elem.key === date)
      if (found) found.val += cur.val;
      else accumulator.push(cur);
      return accumulator;
    }, []);
    
    console.log(output)

    0 讨论(0)
  • 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);
    <script src="http://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script>

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

    0 讨论(0)
  • 2020-11-22 05:40
    var targetObj = {};
    for (var i = 0; i < objArr.length; i++) {
        if (!targetObj.hasOwnProperty(objArr[i].key)) {
            targetObj[objArr[i].key] = 0;
        }
        targetObj[objArr[i].key] += objArr[i].val;
    }
    

    http://jsfiddle.net/HUMxp/

    0 讨论(0)
提交回复
热议问题