使用underscorejs扩展对象

时间:2016-08-31 20:02:00

标签: underscore.js

我有一个对象数组。 weightedAverage属性需要更新。最初weightedAverage设置为0.请参阅下面的脚本以获取更多详细信息。

预期输出是:

[
      {
        area:"Digital",
        category:"Medical",
        qId:"wRHmpHHGzrYLsCEJ32",
        qqId:"step1",
        type:"Reduce",
        val:1,
        **weightedAverage:80**
      }
];

脚本

var arrayFlatten = [
      {
        area:"Digital",
        category:"Medical",
        qId:"wRHmpHHGzrYLsCEJ32",
        qqId:"step1",
        type:"Reduce",
        val:1,
        weightedAverage:0
      },
      {
        area:"Digital",
        category:"Analytics",
        qId:"wRHmpHHGzrYLsCEJ32",
        qqId:"step1",
        type:"Reduce",
        val:1,
        weightedAverage:0
      },
      {
        area:"Digtal",
        category:"Medical",
        qId:"wRHmpHHGzrYLsCEJ32",
        qqId:"step1",
        type:"Reduce",
        val:10,
        weightedAverage:0
      }
    ];


    //groupBy qid
    var groupqId = _.groupBy(arrayFlatten,'qId');
    console.log(groupqId);
    //value dividedby total value
    var result = {};
    _.each(groupqId, function(val, key) {
      console.log(val);
        result.qId=key;
        result.weightedAverage = _.reduce(val, function(memo, v) {
          console.log(v);
          return memo + v.val;
        }, 0) / 15 * 100;
    });
    console.log(result);

1 个答案:

答案 0 :(得分:0)

您只需通过简单的循环

即可
var final=[];
for(var i = 0 ; i < arrayFlatten.length ; i++){
  arrayFlatten[i].weightedAverage = 80;
    final.push(arrayFlatten[i]);
}
console.log("FINAL",final);