Reputation: 15
I have a problem with JavaScript. The code is as follows:
var myDB = [
{ xCounter: 'positive', day: 'first' },
{ xCounter: 'positive', day: 'second' }
];
var days = _.groupBy(myDB, 'day');
How can I get the first, second, third... value of "days"?
Thanks!
Upvotes: 1
Views: 442
Reputation: 791
According to the example you gave:
var myDB = [{ "xCounter": "positive", "day": "first" }, { "xCounter": "positive", "day": "second" }];
Using the groupBy
method, you'll get the following result in the days
variable:
{
first: [{ "xCounter": "positive", "day": "first" }],
second: [{ "xCounter": "positive", "day": "second" }]
}
To go through this result, you can use the following snippet:
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: I'd suggest using Lodash instead of Underscore if possible (https://lodash.com/docs/4.16.1#groupBy) as Lodash development is more active, but that's my opinion ;)
Upvotes: 1