Search code examples
javascriptarraysstringecmascript-6lodash

How to deal with searching strings and array of strings in JS


_.get(params, "_q") outputs either string or array of strings. On my current code, when I type for example "hello, there", it translates to array of strings and as a result is says something like h.get(...).trim is not a function.

Pls see my current code below. and what i've tried so far. Is my tried code good or is there a better way using modern JS?

Note: _ is from lodash.

Result of console.log(params) when typing "hello, there"

{
    "_q": [
        "hello",
        " there "
    ]
}

Result of console.log(params) when typing "hello"

{
    "_q": "hello"
}

Result of console.log(params) when typing "hello there"

{
    "_q": "hello there"
}

Current code

 let where = {};

  if (_.get(params, "_q")) {
    where._q = _.get(params, "_q").trim();
  }

What fix I have tried so far

  const _q = _.get(params, "_q");
  if (_q) {
    where._q = []
      .concat(_q)
      .map((str) => str.split(",").map((str) => str.trim()))
      .flat();
  }

Solution

  • I see, the "input", e.g. the "_q" property value can be either a single string, or an array of strings.

    I'd suggest plopping params._q into an array and flatten it first, then map the strings in the array to a new array of trimmed string values.

    Example:

    [get(params, "_q")].flat().map((el) => el.trim())
    

    Given:

    • Array of strings

      const params = {
        _q: ["hello", " there "]
      };
      
      [get(params, "_q")]       // [["hello", " there "]]
        .flat()                 // ["hello", " there "]
        .map((el) => el.trim()) // ["hello", "there"]
      
    • String

      const params = {
        _q: " hello there "
      };
      
      [get(params, "_q")]       // [" hello there "]
        .flat()                 // [" hello there "]
        .map((el) => el.trim()) // ["hello there"]
      

    Demo

    const params = {
      _q: ["hello", " there "]
    };
    
    console.log([params._q].flat().map((el) => el.trim())); // ["hello", "there"]