Why doesn't Lodash's map method work in implicit chains?

Viewed 30

Given an object that looks like this:

let obj = { mytest: [{ mytest2: 123 }] }

I would have thought I could use the implicit chain like this:

_(obj).get('mytest').map('mytest2').value();

But I get an error:

VM922:1 Uncaught TypeError: mytest2 is not a function
    at Array.map (<anonymous>)
    at <anonymous>:1:22
(anonymous) @ VM922:1

It seems to expect the map parameter to be a function. If I use the explicit chain method then it does seem to work.

_.chain(obj).get('mytest').map('mytest2').value();
[123]

What's going on here? I'm using lodash 4.17.15.

1 Answers

The _(obj) is not an "implicit chain", it's a use-once object that wraps a value to make lodash functions available with method syntax. _(obj).get('mytest') is the same as _.get(obj, 'mytest'), and returns the raw [{ mytest2: 123 }] array. The .map method you're calling is not _.map, it's the array map method which requires a function argument. You also wouldn't need to call .value() on the return value.

Related