Why does this JSX only display the most recent item I included in the object?

Within my function for constructing a search filter, there is the following logic:

    const filter = {
      $and: [
        req.query.category !== "" ? { category: req.query.category } : {},
        req.query.subCategory !== "" ? { tags: req.query.subCategory } : {},
        req.query.contentType !== ""
          ? {
              contentType: req.query.contentType,
            }
          : {},
        req.query.searchTerm !== ""
          ? ({
              name: {
                $regex: "(?i)" + req.query.searchTerm + "(?-i)",
                $options: "i",
              },
            },
            {
              tags: {
                $regex: "(?i)" + req.query.searchTerm + "(?-i)",
                $options: "i",
              },
            },
            {
              description: {
                $regex: "(?i)" + req.query.searchTerm + "(?-i)",
                $options: "i",
              },
           
            })
          : {},
      ],
    };

After executing console.log(filter), the result consistently shows an array of objects with all empty properties except for the last one, which retains its structure. If I modify the order or remove certain properties like this:

 {
              description: {
                $regex: "(?i)" + req.query.searchTerm + "(?-i)",
                $options: "i",
              },
            },
            {
              tags: {
                $regex: "(?i)" + req.query.searchTerm + "(?-i)",
                $options: "i",
              },
            }

, the outcome remains consistent with only the last object retaining its data

{ '$and': [ {}, {}, {}, { tags: [Object] } ] }
.

What could be causing this pattern of empty objects in the array?

Answer №1

If you want to separate the items for req.query.searchTerm, consider using this method:

const filter = {
  $and: [
    req.query.category !== "" ? { category: req.query.category } : {},
    req.query.subCategory !== "" ? { tags: req.query.subCategory } : {},
    req.query.contentType !== ""
      ? {
          contentType: req.query.contentType,
        }
      : {},
    req.query.searchTerm !== ""
      ? {
          name: {
            $regex: "(?i)" + req.query.searchTerm + "(?-i)",
            $options: "i",
          },
        } : {},
    req.query.searchTerm !== ""
      ? {
          tags: {
            $regex: "(?i)" + req.query.searchTerm + "(?-i)",
            $options: "i",
          },
        } : {},
    req.query.searchTerm !== ""
      ? {
          description: {
            $regex: "(?i)" + req.query.searchTerm + "(?-i)",
            $options: "i",
          },
        } : {},
  ],
};

Keep in mind that this approach will result in a total of 6 items in the $and array.

Answer №2

You should determine the structure of your return object.

Here is a snippet of your current code:

if (searchTerm !== '') {
   return( { a: 'a' } , { b: 'b' } , { c: 'c' } ); // returns { c: 'c' }
}

Perhaps you intended to return something like this instead:

if (searchTerm !== '') {
   return( { a: 'a' , b: 'b' , c: 'c' } ); // returns 1 object with all 3 properties
           ^                          ^
}
        req.query.searchTerm !== ""
          ? ({ // added a {
              name: {
                $regex: "(?i)" + req.query.searchTerm + "(?-i)",
                $options: "i",
              },
            //},
            //{
              tags: {
                $regex: "(?i)" + req.query.searchTerm + "(?-i)",
                $options: "i",
              },
            //},
            //{
              description: {
                $regex: "(?i)" + req.query.searchTerm + "(?-i)",
                $options: "i",
              },
            //}
          }) // added a }
          : {},

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

Mastering the use of getText() in Protractor with Page Object Model in Javascript

Having trouble retrieving specific values from my page object. The getText() method is returning the entire object instead of just the text, likely due to it being a Promise. I can provide my code if necessary, but I'm aiming to achieve something sim ...

Tips for updating the version number in a non-integer JSON format

Every time I run this code, I want it to update the JSON file. The problem: 1. The version in the JSON file is stored as a string rather than an integer Solution: I plan to extract the version number, convert it to an integer by removing the periods, ...

Communicate with a PHP page using Volley for both sending and receiving data

I am planning to pass a parameter to a PHP page, and after performing specific processing on it, I want to receive a series of parameters in JSON format from the same page. Below is the code I have written for this: //Displaying progress dialog final Prog ...

What is the process for comprehending an event that is not triggered by the task queue within the event loop specifications?

According to the guidelines: Various events are triggered through tasks apart from just the task queue. I am curious to understand what exactly is meant by "various" and the specific types of tasks being referred to here? ...

Rearrange the order of items in the fancybox gallery

Typically, fancybox displays items in the gallery based on the order they are added in the HTML code. Is there a way to customize the order of items when they are opened in the popup, while keeping the original order when displayed on the page? The solut ...

What steps should I take to ensure my button functions correctly after I have finished writing?

I am attempting to create blog buttons that will input text into a textarea when clicked. However, I am experiencing an issue where the text won't be added if I have already been typing or editing in the textarea before clicking the button. <butto ...

There is a problem with the Angular document because it is not

I am looking to optimize my Angular app for production by running the following command: npm run build:ssr SSR stands for server-side rendering. However, after completing the build process, I encounter an error within my header components. The error mes ...

If the div is devoid of content, then remove the class

<div class="slider">content goes here</div> <div id="slider-2" class="active inactive">also some content here</div> <script type="text/javascript"> function checkEmpty( element ){ return !$.trim(element.html()) ...

When "this" doesn't refer to the current object, how to self reference an object

I am currently working on developing a modular series of element handlers for an application that features pages with different configurations. For example, the 'Hex T' configuration includes elements labeled from 'A' to 'O', ...

Java JSON Testing Suite for Serialization and Deserialization

Does anyone know of any widely used JSON unit tests that I could adapt for my library? I've created some basic tests for my JSON serialization and deserialization functions, but I'm worried I may have overlooked some edge cases. Though my curren ...

Sending JSON data object to a server in iOS7: A step-by-step guide

Hey there, I've been working on an application where I stored data in a local sqlite3 database. Now, my task is to transfer this data from the local database to an online server. To achieve this, I used a dataDictionary for retrieving all the data fro ...

What is the best way to transform a database object into a complex JSON structure?

My goal is to retrieve a specific person from a list of persons. The POST method works correctly and I am able to obtain the desired person as "chosenPerson" in the controller. However, when I try to convert this person into a complex JSON object using ser ...

Shuffle order of AngularJS ng-repeat array

I am struggling to create a basic grammar quiz where I need to randomly sort an array using ng-repeat. The goal is to display both correct and incorrect sentences in random order. Below you can find my code snippet: (function(angular) { 'use str ...

Tips for simulating a dropdown selection from a remote location

I have multiple dropdown selection menus where changing the option in one menu affects the options in the next menu, and so on. I want to programmatically trigger a change (without user interaction) in the dropdown menu that will activate the JavaScript f ...

How to determine the number of events scheduled for a specific time frame using a full calendar display

Hey there! I am currently incorporating jQuery FullCalendar into my application. While reviewing the code, I came across this specific line: var sameDayList = view.eachElementOnDay(event); This line allows me to retrieve a list of all events on a particu ...

Using grid-template-areas in ReactJS function components does not function as expected

REMINDER: Check out and customize the code in CodeSandbox. This is a parent component with 5 children elements. Among them, 3 are React components and the remaining 2 are regular HTML buttons: import "./App.css"; import React from "react&qu ...

unexpected behavior when using jquery click function

I am currently working on a unique custom radio element that showcases images instead of the standard radio buttons. The basic HTML structure looks like this: <div id="wrap"> <p></p> <input type="radio" data-check='class-c ...

Ajax request and the Ghostery extension in Firefox

I've implemented the following code to detect ad blockers like Ghostery: <script> var request = new XMLHttpRequest(); request.onreadystatechange = function() { if(request.readyState === 4 && request.status === 200 ) { ...

Angular JS Troubleshooting: Application Not Functioning Properly

I've been learning AngularJS on codeSchool and I ran into an issue with my simple hello world app. It was working fine at first but then stopped completely. I can't seem to find the bug, so any help would be appreciated. Here is the HTML code: & ...

AngularJS is behaving in a way that requests fresh JSON data only during the initial loading

I'm currently utilizing AngularJS to incorporate an app into a native iOS application, but I'm encountering difficulties with loading dynamic data. I have configured the controllers to retrieve JSON data from the iOS app via http queries for eac ...