Search code examples
javascriptfilterlodashchain

Using Lodash chain and filter not returning filtered value


I am trying to use LoDash to filter an object where the key state === accepted. There are two objects in the quoteList array. The console.log is returning 2 objects in the array; I am expecting it to return 1 object where state === accepted. I am using chain because I will need to use other functions once I get this working.

let quoteList = shipment.quotes
const QuoteSlides = _
.chain(quoteList)
.filter(['state', 'accepted'])
console.log(quoteList)

Solution

  • Though you're logging the incorrect object (as mentioned in comments by @Baruch), you also have to unwrap the result using .value() function to get the actual result:

    const QuoteSlides = _
      .chain(quoteList)
      .filter(['state', 'accepted'])
      .value()
    

    Lodash creates a wrapper when you call _.chain on an object. This is called explicit chaining. .value() removes the wrapper and returns the actual result, which will be assigned to QuoteSlides.

    See more of implicit and explicit chain sequences.