获取_.groupBy的值

时间:2016-09-25 13:02:36

标签: javascript underscore.js

我遇到了JavaScript问题。代码如下:

var myDB = [
    { xCounter: 'positive', day: 'first' }, 
    { xCounter: 'positive', day: 'second' }
];

var days = _.groupBy(myDB, 'day');

如何获得"天"的第一,第二,第三......值?

谢谢!

1 个答案:

答案 0 :(得分:1)

根据你给出的例子:

var myDB =  [{ "xCounter": "positive", "day": "first" }, { "xCounter": "positive", "day": "second" }];

使用groupBy方法,您会在days变量中获得以下结果:

{
  first: [{ "xCounter": "positive", "day": "first" }],
  second: [{ "xCounter": "positive", "day": "second" }]
}

要完成此结果,您可以使用以下代码段:

for (var day in days) {
  if (days.hasOwnProperty(day)) {
    // do something with 'day' (which will take tha values 'first' and 'second')
    // and 'days[day]' (which is an array of {xCounter: X, day: Y} objects)
  }
}

PS:我建议尽可能使用Lodash代替Underscore(https://lodash.com/docs/4.16.1#groupBy),因为Lodash开发更活跃,但这是我的看法;)