使用Underscore填充数组中缺少的对象

时间:2016-09-03 01:42:27

标签: javascript underscore.js javascript-objects

我正在玩一个数据集,该数据集计算一个人在某个小时的提交次数。我可以为一个人提交的小时和他们提交的次数创建一个数组对象:

[ { hour: '6', commits: 2 },
  { hour: '7', commits: 6 },
  { hour: '8', commits: 6 },
  { hour: '9', commits: 4 },
  { hour: '10', commits: 4 },
  { hour: '11', commits: 6 },
  { hour: '12', commits: 18 },
  { hour: '13', commits: 18 },
  { hour: '14', commits: 14 },
  { hour: '15', commits: 30 },
  { hour: '16', commits: 24 },
  { hour: '17', commits: 18 },
  { hour: '18', commits: 24 },
  { hour: '19', commits: 22 },
  { hour: '20', commits: 6 },
  { hour: '21', commits: 16 },
  { hour: '22', commits: 8 } ]

我被困在哪里试图填补缺少的时间。所以在上面的例子中,我需要包括没有提交的小时数。我整天都在使用0-24范围。这就是我希望得到的结果:

[
  { hour: '0', commits: 0 }, 
  { hour: '1', commits: 0 },
  { hour: '2', commits: 0 },
  { hour: '3', commits: 0 },
  { hour: '4', commits: 0 },
  { hour: '5', commits: 0 },
  { hour: '6', commits: 2 },
  { hour: '7', commits: 6 },
  { hour: '8', commits: 6 },
  { hour: '9', commits: 4 },
  { hour: '10', commits: 4 },
  { hour: '11', commits: 6 },
  { hour: '12', commits: 18 },
  { hour: '13', commits: 18 },
  { hour: '14', commits: 14 },
  { hour: '15', commits: 30 },
  { hour: '16', commits: 24 },
  { hour: '17', commits: 18 },
  { hour: '18', commits: 24 },
  { hour: '19', commits: 22 },
  { hour: '20', commits: 6 },
  { hour: '21', commits: 16 },
  { hour: '22', commits: 8 },
  { hour: '23', commits: 0 },
  { hour: '24', commits: 0 }
]

这是我用来创建这些对象的函数:

var getAuthorAndHourCounts = (groupedByAuthor) => {

  var result = _.map(groupByAuthor, (value, key, list) => {

    var author = key;
    var hours = _.countBy(value, 'hour');

    var commitHourList = [];

    _.each(hours, (v,k) => {
      var obj = {};
      obj.hour = k;
      obj.commits = v;
      commitHourList.push(obj);
    });

    return {
      person: author,
      times: commitHourList
    };

  });
  return result;
};

如何添加缺失的时间?我正在考虑创建一个列表(0-24)然后查看列表中是否有一个小时将其添加到对象的值为零。不知道如何实现。

1 个答案:

答案 0 :(得分:3)

如何初始化commitHourList,使其包含0次提交的所有小时数,然后将其填入实际数据:

// initialize commitHourList with 24 objects 
// one for each hour and each with 0 commits
var commitHourList = _.range(24).map((hour) => ({ hour, commits: 0 }));

// for every received hour, add proper commits
_.each(hours, (commits, hour) => {
  commitHourList[hour].commits = commits;
});

这样,无论您何时添加,都会自动提交0次。

注意:使用range然后map初始化数组的代码较少,但每次迭代数组两次。一种更高效的方法是在某个实用程序中创建一次该数组,然后在每次需要新数组时复制它。

例如:

// utility that creates the hours array when initialized
// and returns a function that will return a copy of the hours array on each call
var getHoursArray = (function() {
  var arr =  _.range(24).map((hour) => ({ hour, commits: 0 }));
  return function() {
    return arr.slice();
  }
})();

然后使用它:

var commitHourList = getHoursArray();

使用slice通常是复制数组的最佳方式,但here are other possibilities