Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining pluck() and flatten() with lodash

This works, but how can I chain it?...

allWeeks = _.flatten(_.pluck(dates.months, 'weeks'))
allDays  = _.flatten(_.pluck(allWeeks, 'days'))

I've tried:

allDays = _.chain(dates.months).pluck('weeks').flatten().pluck('days').flatten()

And this:

allDays = _(dates.months).pluck('weeks').flatten().pluck('days').flatten()
like image 336
Gil Birman Avatar asked Feb 20 '14 21:02

Gil Birman


2 Answers

Instead of deleting this question out of sheer embarrassment, I will leave the answer here for any other poor schmuck out there wondering "why the heck isn't my lodash chain working?!":

You must end the chain with .value()

so this:

allDays = _.chain(dates.months).pluck('weeks').flatten().pluck('days').flatten().value()

and this:

allDays = _(dates.months).pluck('weeks').flatten().pluck('days').flatten().value()
like image 75
Gil Birman Avatar answered Oct 22 '22 12:10

Gil Birman


You have to know that starting for Lodash 4.0.0, _.pluck() is replaced by _.map() so for example:

var objects = [{ 'a': 1 }, { 'a': 2 }];

// in 3.10.1
_.pluck(objects, 'a'); // → [1, 2]
_.map(objects, 'a'); // → [1, 2]

// in 4.0.0
_.map(objects, 'a'); // → [1, 2]
like image 5
Mazen Aly Avatar answered Oct 22 '22 11:10

Mazen Aly