Tips for handling searches for strings and arrays of strings in JavaScript

_.get(params, "_q") can output either a string or an array of strings. In my current code, when I input "hello, there", it translates to an array of strings and results in an error saying

h.get(...).trim is not a function
.

Please take a look at my current code below and what I have attempted so far. Is my attempted solution sufficient, or is there a more modern JS approach?

Note: _ refers to lodash.

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

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

Result of console.log(params) for "hello"

{
    "_q": "hello"
}

Result of console.log(params) for "hello there"

{
    "_q": "hello there"
}

Current code

 let where = {};

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

Fixes I have attempted

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

Answer №1

It appears that the value of the "input", specifically the "_q" property, can be either a single string or an array of strings.

My recommendation would be to place params._q into an array, flatten it first, and then map the strings in the array to a new array containing trimmed string values.

For instance:

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

Example scenarios:

  • 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"]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Deactivating upcoming weeks according to the year in Angular 8

In the user interface, there are dropdowns for selecting a year and a week. Once a year is selected, the list of weeks for that year is displayed in the week dropdown. Now, the requirement is to disable the selection of future weeks. For example, for the ...

Difficulty updating Material UI table

Currently in the process of updating my react site to version 16.8, I have encountered an issue with a material ui table. The functionality involves users selecting certain options, triggering a rest call when a button is clicked, and then displaying the r ...

Determine if a given text is present in an array of strings in the C programming language

Looking for some guidance as I delve into the world of C programming. I have a task where I need to prompt the user to input 5 colors into an array, but I need to verify if the color already exists in a list of allowed colors before adding it. I've e ...

A TypeScript method for accessing deeply nested properties within an object

I'm currently working on a function that utilizes typings to extract values from a nested object. With the help of this post, I managed to set up the typing for two levels successfully. However, when I introduce a third (known) level between the exis ...

When using the React Material Tree Table, I expect any new row added to automatically expand by default in the table tree structure

<MaterialTable title="title" columns={columns} data={data} icons={tableIcons} parentChildData={(row, rows) => rows.filter((item) => item.id === row.productId)} /> ...

Issue with React.js: The formData is empty when trying to add a value from a file using material-ui-dropzone

I am currently working on integrating an upload feature using a library named material-ui-dropzone Although I believe the file upload process is functioning correctly, I encounter an issue with axios where the formData appears empty even prior to sending ...

What is the best method for sending a JavaScript variable to the server and back again?

I'm currently working on a JavaScript project where I need to build a string. Let's say, for the sake of this example: var cereal = 'my awesome string'; There's also a button on my webpage: <button id="send" type="submit" nam ...

When implementing 'useGlobalGuards' in NestJS, remember to exclude endpoints for enhanced security

After implementing the useGlobalGuards method in my main.ts file, all endpoints now utilize the AuthGuard. This guard triggers a 401 error if a valid auth token is not present in the request header. Previously, I used @UseGuards(AuthGuard) on individual cl ...

Obtain the closest numerical range using JavaScript

I have a range object and an array of price values. My goal is to find the nearest range from the range object for each value in the price values array. I attempted the solution below, but it did not give me the correct range. range = { 0: '25-500 ...

Avoid using "DOT" as an input type for numbers on mobile devices

Currently, I am working with jQueryMobile and PhoneGap. I have encountered an issue that I have been unable to find a solution for. The problem is that I need to prevent users from typing a DOT in a textbox that is specifically meant for entering their age ...

Verify whether the number of minutes aligns with a full hour mark (60, 120, 180, 240 minutes, etc)

Query Determine if a given number of minutes equates to an exact hour or multiple hours. Scenario I am currently working on a script where I need to ascertain whether a certain number of seconds corresponds to an hour or x hours; returning true if it doe ...

I'm trying to figure out how to incorporate this code into an arrow function while also utilizing the iterating array element

I am aiming to create a function that can provide either true or false based on whether the searchElement exists in the array. While I could achieve this with a simple for loop and if-else statement, my goal is to utilize an arrow function. Although JavaS ...

Attention required prior to closing the (x) button on a Chrome modal popup alert

I've been attempting to close the popup modal confirm alert using various methods, but unfortunately none have been successful. I tried using popupcsd.onbeforeunload and popupcsd.onUnload, with no luck. The code snippet I'm working with is: wind ...

Using JQuery to append an additional column to an HTML table at the end, determined by array information

I've been experimenting with how to enhance an html table by adding a new column of data. The process involves clicking a button, extracting the existing data column in the table, storing it in an array, performing calculations on it, and then display ...

Which specific class appears to be absent from the code snippet provided above?

class Test { int findUnique(int arr[],int n) { int result=0; for(int i=0;i<n;i++) { int sum=0; x=(1<<i); for(int j=0;j<n;j++) { if(arr[j]&x) sum++; } if ...

Error came up as "backbone.radio.js" and it threw Uncaught SyntaxError since the token import appeared unexpectedly

I've been struggling to transition an application from Backbone to Marionette (v3) for the past two days. Every time I try to run the app in the browser, I keep encountering this error in the console (resulting in a blank screen): Uncaught SyntaxErr ...

Jquery draggable droppable does not support displaying multiple divs simultaneously

I tried to implement the jquery ui draggable and droppable features to display 3 divs within a designated area. Below is the code snippet: --CSS: #content-1 { width: 200px; height: 100px; border: 1px solid red; display: none; } #content-2 { width: ...

Storing array elements within an array: best practices

I am trying to store an array in an element by using a 2-D array, but I'm facing issues. I need to handle 5 IEEE addresses, each consisting of 8 bytes. I want to store them one by one as they are received. char a[5][8]; int i = 0; if(data) { a[i] = ...

Attempting to extract information from an array of strings containing the URL of an API

I am looking to extract data from an array that contains APIs, but the issue is that the number of APIs in the array varies. For example, some arrays may have 3 API addresses while others have just 2. { "name": "CR90 corvette", "m ...

How can I utilize JavaScript on the server-side similar to embedding it within HTML like PHP?

One aspect of PHP that I find both intriguing and frustrating is its ability to be embedded within HTML code. It offers the advantage of being able to visualize the flow of my code, but it can also result in messy and convoluted code that is challenging to ...