Search code examples
javascriptlodashchaining

Use Lodash chain on single value


I want to chain some methods on a single string so that string manipulation looks more readable.

But it seems that chain() works only on collections.

It's not a problem, I just wrap it into array, but to take the final value I have to use zero index operator which looks weird here.

var res = _(["   test   "])
   .map(function(s) { return s + s; })
   .map(_.trim)
   .value()[0];

or TypeScript:

var res = _(["   test   "])
   .map(s => s + s)
   .map(_.trim)
   .value()[0];

How to resolve it?


Solution

  • The solution was to use head() instead of value():

    var res = _(["   test   "])
       .map(function(s) { return s + s; })
       .map(_.trim)
       .head();
    

    or TypeScript:

    var res = _(["   test   "])
       .map(s => s + s)
       .map(_.trim)
       .head();
    

    This way res is just a string, and the code is more readable.