我的 JavaScript 有问题。代码如下:
var myDB = [
{ xCounter: 'positive', day: 'first' },
{ xCounter: 'positive', day: 'second' }
];
var days = _.groupBy(myDB, 'day');
如何获得“天”的第一个、第二个、第三个...值?
谢谢!
最佳答案
根据您给出的示例:
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 开发更加活跃,但这是我的观点;)
关于javascript - 获取_.groupBy的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39687131/