如何对对象的值求和并将其推入数组

时间:2015-07-15 02:45:15

标签: javascript arrays object d3.js

我有一个动态的对象数组,它取决于表的行的选择。一个例子:

var obj = [
            { name: "test1",  totalCosts: 45560, actualTotalCosts: 652112, riskCosts: 65442 },
            { name: "test2",  totalCosts: 3434,  actualTotalCosts: 25252,   riskCosts: 34234 },
            { name: "test3",  totalCosts: 23123, actualTotalCosts: 23242,  riskCosts: 0 },
        ];

生成此数组后,我想调用一个函数,该函数在该数组中再推一行并命名为" total"并总结所有受尊重的值,如下所示:

  

{name:" total",totalCosts:72117,actualTotalCosts:700606,risksCosts:99676}

     

obj [0] .totalCosts + obj [1] .totalCosts + obj [2] .totalCosts = obj [3] .totalCosts

我尝试用我有限的知识写一个,但是这个函数不是总结所有三个对象的值,而是将整个对象概括为一个。

            function sum1( obj ) {
            var result1 = [];
            for (var i = 0; i < obj.length; i++) {
                var sum = 0, arr = [];
                for (var key in obj[i]) {
                    if (key != 'name') {
                        sum += obj[i][key];
                        arr.push(sum[key]);
                    }

                }
                result1.push(arr);
                return result1;
            }
        }

请提供一个函数,它可以汇总所有对象并返回数组与总数。我也尝试过使用d3.sum,但没有成功。

2 个答案:

答案 0 :(得分:3)

注意:了解您所谓的var obj实际上是一个数组非常重要。

话虽这么说,你可以迭代你的数组并执行此操作:

function sumAll(arr) {

  // Create variables for the costs we're tracking
  var totalCosts = 0;
  var actualTotalCosts = 0;
  var riskCosts = 0;

  arr.forEach(function(elem) {
    // At each iteration of our loop, increase the appropriate variables by their appropriate values
    if (elem.hasOwnProperty('totalCosts')) {
      totalCosts += elem.totalCosts;
    }
    if (elem.hasOwnProperty('actualTotalCosts')) {
    actualTotalCosts += elem.actualTotalCosts;
    }
    if (elem.hasOwnProperty('riskCosts')) {
      riskCosts += elem.riskCosts
    }
  });

  // Return an object with the information we'd like to have
  return {
    name: 'total',
    totalCosts: totalCosts,
    actualTotalCosts: actualTotalCosts,
    riskCosts: riskCosts
  }
}

从你的代码:

var obj = [
            { name: "test1",  totalCosts: 45560, actualTotalCosts: 652112, riskCosts: 65442 },
            { name: "test2",  totalCosts: 3434,  actualTotalCosts: 25252,   riskCosts: 34234 },
            { name: "test3",  totalCosts: 23123, actualTotalCosts: 23242,  riskCosts: 0 },
        ];

调用我的功能:

sumAll(obj) // {name: "total", totalCosts: 72117, actualTotalCosts: 700606, riskCosts: 99676}

答案 1 :(得分:3)

您可以借助d3.sum ...

采取功能性方法
  (function() {
    var obj = [{
      name: "test1",
      name2: "type1",
      totalCosts: 45560,
      actualTotalCosts: 652112,
      riskCosts: 65442
    }, {
      name: "test2",
      name2: "type2",
      totalCosts: 3434,
      actualTotalCosts: 25252,
      riskCosts: 34234
    }, {
      name: "test3",
      name2: "type3",
      totalCosts: 23123,
      actualTotalCosts: 23242,
      riskCosts: 0
    }];

    obj.push(d3.keys(obj[0])
      .reduce(function(sumRow, sumCol) {
        var isNum = !isNaN(obj[0][sumCol])
        return (sumRow[sumCol] = (isNum ? d3.sum(obj, function(row) {
          return row[sumCol]
        }) : "All"), sumRow)
      }, {}));

    d3.select("#result").text(JSON.stringify(obj))
  })()

工作示例

&#13;
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="result"></div>
&#13;
ssh
&#13;
&#13;
&#13;

相关问题