How do you chain functions using lodash?

Datsik picture Datsik · Feb 24, 2016 · Viewed 56.2k times · Source

I have an object that looks like

var foundUser = {
    charData: []
}

which then I load an object from a database using mysql and then I call

_.assignIn(foundUser, rows[0]);

But I get a few extra properties that I don't need (this isn't solvable by using select)

So I call

foundUser = _.omit(foundUser, ['blah']);

But it would be nice if I could just do

_.assignIn(foundUser, rows[0]).omit(rows[0], ['blah']);

But that throws an error, am I doing it wrong or is there another way this can be done?

Answer

Kenneth picture Kenneth · Feb 24, 2016

To chain with lodash, you first have to wrap the object:

_(foundUser).assignIn(rows[0]).omit(['blah']).value();

Further clarification:

The _ creates a lodash object which allows for implicit method chaining. Implicit method chaining means that in certain circumstances it may return a primitive value, in others it may return a lodash object that you need to unwrap by calling .value() on it.

If you'd use _.chain(...), you'd be creating a lodash object with explicit method chaining. The result is always a wrapped value and always needs to be unwrapped by calling .value() on it.

For further reference here are the links to the documentation:

Explicit chaining in Lodash

Implicit chaining in Lodash