`When using indexOf to search a JSON object, the result may return as

Within my messages.json file, I have JSON objects storing chat messages. An example snippet is shown below:

[
  {
    "sender": "Alice",
    "text": "Hello there"
  },
  {
    "sender": "John",
    "text": "How's it going?"
  }
]

I am trying to locate the index of a specific term within these messages based on user input from a text field. However, running the code snippet below results in receiving "undefined" in the output console.

const handleSearch = (event) => {
  const searchResult = messages.filter((message) => {
    return message.text.indexOf(event.target.value);
  });
  console.log(searchResult);
};

What could be causing this unexpected "undefined" outcome?

Answer №1

The indexOf function will return a value of 0 if it finds the search term at the beginning of the string, which is considered false in JavaScript logic. To ensure accurate results, you can use the following code:

return message.text.indexOf(event.target.value) > -1

Answer №2

indexOf() gives a 0-based index, so ensure to convert it to boolean to avoid incorrect results. Additionally, event.target.value could be empty or in a different case.

I suggest verifying the existence of both values and converting them to the same case with toLowerCase() before comparing them.

const messages = [{
    "sender": "Alice",
    "text": "Hello there"
  },
  {
    "sender": "John",
    "text": "Hey, what's up?"
  }
]

const result = messages.filter((message) => {
  return message.text.toLowerCase().indexOf("hey") >= 0;
});
console.log(result);

Answer №3

When dealing with an array of messages, the indexOf method is not sufficient for finding a single message. Instead, use the find() method for this purpose. If you need to find multiple instances, consider using the filter() method.

   const handleInput = (event) => {
          const result = messages.find(i=>i.text.toLowerCase().indexOf(event.target.value.toLowerCase()));
          console.log(result);
        };

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

Using jQuery Accordion within the MVC Framework

I'm new to MVC and considering using an accordion. However, I'm facing issues as the accordion does not appear despite adding all necessary references for jquery accordion and creating the div. Here is my code: @{ ViewBag.Title = "Online Co ...

Error message: "Module not found" encountered while executing test case

I am a beginner in node and nightwatch and I have followed all the initial instructions from setting up node, npm, selenium standalone, starting the selenium driver. I also downloaded the chrome driver and placed it in the same directory. I created the con ...

What is the reasoning behind the "open in a new tab" function triggering a GET request?

Check out this HTML tag: <a href="#" id="navBar_navBarInput_3_subNavDropdownInput_0_subNavLinkInput_0" onclick="redirectPost(4,'EntryData.aspx');">My Cool Link</a> The Javascript function "redirectPost" function redirectPost(id, ur ...

Streaming JSON objects through a WCF REST service

Is there a way to create a Windows service where a REST API can dump JSON objects into a stream with the content-type of application/stream+json? Here's an example response (not an array of objects): { id: 1, name: "name 1" } { id: 2, name: ...

Reactjs throwing an Unsupported Media Type error with code 415

I am currently working on implementing a delete function to remove banner images. Here is the code snippet for my delete function: const [del, setDel] = useState([]); const DeleteBanner = async (banner) => { setDel(banner); ...

Is it possible to invoke the function `this.function` within the same file where it is declared?

During our project, we set out to develop a Protractor framework. In the JavaScript file, we created some functions using the 'this.functionname' syntax with the intention of reusing these functions when needed within the same file. For better cl ...

Encountering an issue where the Angular build is unable to locate the installed Font-Awesome node module

Every time I attempt to compile my project using ng build --prod, I encounter the following error: ERROR in ./src/styles.scss Module build failed: ModuleBuildError: Module build failed: Error: Can't resolve '~font-awesome/css/font-awesom ...

Scroll effortlessly to the middle, bottom, and top of the page in vue.js using arrow keys for a seamless

I'm interested in implementing a feature that allows users to scroll smoothly up and down the page using the arrow keys. When the first down key is pressed, I'd like to smoothly scroll to the middle (50%) of the page, and when the second down ...

Getting the text from an element in Protractor that does not have a class or id

I am facing an issue with retrieving text from an element that does not have a class assigned to it. Below is the HTML code snippet: <div><em>Min Amount Required is 150,000</em></div> This is my page object: var minAmount = el ...

Unique custom navigation bar (priority menu) crafted with Bootstrap 5 without any reliance on JQuery technology

Looking to craft a unique Bootstrap 5 custom responsive navbar (priority nav) with a "show More..." feature using Vanilla JS because I have numerous menu items and can't utilize jQuery. Bootstrap navbars don't adapt well to varying screen widths ...

Leveraging various libraries in React

My query revolves around a React application where I have integrated Material UI for only two components. Despite installing the entire Material UI library, will this lead to an increased bundle size for my application? Or does the build process only inc ...

Capturing HTTP requests using JavaScript

I am looking to modify all my ajax requests by intercepting them and changing POST methods before they go out. To intercept all my ajax calls, I can do the following: $.ajaxSetup({ beforeSend: function() { alert('sending...'); } ...

Create a customizable JavaScript clock that synchronizes with an image to display the current hour, minute

I am having trouble with my clock not working I have created images for the hour, minute, second, and AM/PM https://i.sstatic.net/4zg00.png I attempted to use this code: <script language="JavaScript1.1"> <!-- /* Live image clock III Written b ...

Setting a radio button as default based on a variable value can be accomplished by following a few

I am working with 2 radio buttons and I need to dynamically check one based on a variable value. <input type="radio" name="team" id="team_7" value="7"> <input type="radio" name="team" id="team_8" value="8"> The variable number is set dependin ...

The Jquery scroll function seems to be unable to detect the updated variable value that needs to be passed to

As someone who is not a traditional programmer, I have learned programming by searching on Google or asking questions on Stack Overflow. I am attempting to create an ajax function that will retrieve feeds from a database as the user scrolls, based on the ...

When I use the Put method in Express, I receive a 200 status code, but no changes

Hello everyone, I recently attempted to implement my update function and tested it using Postman. I wanted to update the firstName field, but despite receiving a "HTTP/1.1" 200 response in the console, nothing was actually updated. This is the response bo ...

Tips for converting JSON String data to JSON Number data

Hello everyone, I am facing an issue with converting the 'review' value from String to a numerical format in JSON. This is causing problems when trying to perform calculations, leading to incorrect results. The scenario involves saving user comm ...

What steps can I take to fix the sum function?

My function calculates heart rate targets for sports, but there seems to be an issue in the switch statement. The final sum in the function is not being computed properly. For example, if someone is 20 years old with a resting heart rate of 50 beats per mi ...

Unlock the power of fetching string values in an array with Json using CodeIgniter

In my current CodeIgniter project, I am working with an array where I have stored the studentAbsentId in JSON format as follows: [studentAbsentId] => ["1","2"]. Controller Section public function admin_getabsentlist() { $data = array( "sc ...

Will translating numerous layers of python dictionaries and lists into json create issues for other programming languages attempting to decode them?

In my current research project utilizing Python, one of my primary goals is to ensure that my findings are easily accessible to other researchers. To achieve this, I am converting all my results into JSON format so that individuals working with different p ...