E. Sigfrido E. Sigfrido - 1 year ago 79
Javascript Question

Get values of _.groupBy

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"?


Answer Source

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 ;)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download