Home > OS >  Issues with setting a const using lodash _.map
Issues with setting a const using lodash _.map

Time:10-06

Im trying to set a variable after fetching results from Algolia multipleQueries search options.

The result is an object and i deconstruct it to get me 2 arrays.

And im mapping trough it and setting the return to the array that has "nbHits"

  const results = await algolia
        .multipleQueries(searchOptions, {
          strategy: "stopIfEnoughMatches",
        })
        .then(({ results }) => {
          console.log("Step 1", results);
          _.map(results, result => {
            console.log(" Step 2", _.get(result, "nbHits"));
            if (_.get(result, "nbHits") != 0) {
              console.log(" Step 3", _.get(result, "hits"));
              return _.get(result, "hits");
            }
          });
        });
      console.log("Step 4", results);


Step 1

 [ {
  nbHits: 421,
  hits: 1000,
 }, 
 {
  nbHits: 0,
  hits: 0,
 } ]

Step 2 : 421

Step 3 : "An array with the hits"

Step 2 : 0

Step 4 : Undefined 

What am i doing wrong that makes the return value set the const results to undefined.

This works:

const results = await algolia
        .multipleQueries(searchOptions, {
          strategy: "stopIfEnoughMatches",
        })
      console.log(results);

CodePudding user response:

You need to return the _.map call inside .then() block.

const results = await algolia
  .multipleQueries(searchOptions, {
    strategy: "stopIfEnoughMatches",
  })
  .then(({ results }) => {
    return _.map(results, (result) => {
      if (_.get(result, "nbHits") != 0) {
        return _.get(result, "hits");
      }
    });
  });

As a side note: inside _.map you return a value only if _.get(result, "nbHits") != 0 is true, for other cases you will fill the array with undefined values inside it, so consider using _.filter to get them out.

CodePudding user response:

This fixed it for me, using lodash filter instead

const results = await algolia
        .multipleQueries(searchOptions, {
          strategy: "stopIfEnoughMatches",
        })
        .then(({ results }) => {
          return _.filter(results, result => result.nbHits != 0);
  • Related