Exploring JSON with JavaScript

[
{"lastName":"Noyce","gender":"Male","patientID":19389,"firstName":"Scott","age":"53Y,"},
{"lastName":"noyce724","gender":"Male","patientID":24607,"firstName":"rita","age":"0Y,"}
]

The data above represents a JSON object.

var searchBarInput = TextInput.value;

for (i in recentPatientsList.length) {
 alert(recentPatientsList[i].lastName
}

I am successfully receiving alerts for the last names. Now, I have a text input where users can search for a specific value within the JSON data. In this case, they are searching for the last name value.

How can I extract the input value and use it to search within my JSON data?

Answer №1

Here is an example of how to properly iterate over an array:

var searchBarInput = TextInput.value;

for (var i = 0; i < recentPatientsList.length; ++i) {
 alert(recentPatientsList[i].lastName);
}

It's important to use a for loop with an index variable when iterating over arrays, rather than using the "for ... in" mechanism.

To make a comparison between the text input and the "lastName" field of list entries, you would do something like this:

for (var i = 0; i < recentPatientsList.length; ++i) {
 if (searchBarInput === recentPatientsList[i].lastName) {
   alert("Found at index " + i);
 }
}

Answer №2

Avoid using for..in to loop through arrays; opt for a traditional for loop instead. If you need to retrieve objects with a specific last name, consider filtering the array.

var filteredObjects = patientsArray.filter(function(object) {
    return object.lastName === searchInput;
});

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

When processing fails for the term 'for'

Why is the parsing not working as expected? What could be causing an error in this code? This code used to work with a certain JSON format, but after changing the JSON data, the "for" loop has stopped functioning properly do{ let json = ...

Utilizing multiple UILocalNotifications simultaneously

Hey there, I've encountered an issue with using UILocalNotification. I'm receiving notifications from a server and storing the data in a MutableArray. Here's a snippet of what it looks like: idnoty * id of notification titlenoty * title of ...

I am attempting to retrieve the JSON object value from an error response while making a POST request in my Next.js application

Users can input an email into an input field, which is then sent as a post request to an API using the following code: try { const res = await fetch("/api/email-registration", { method: "POST", headers: { ...

Look for identical values within a nested array

My data consists of a nested array where each element has a property called name, which can only be either A or B. I need to compare all elements and determine if they are all either A or B. Here is an example of the input: [ { "arr": { "teach ...

Export all entries without taking into account pagination limits

My current setup involves using Datatables with pagination. I recently integrated the Datatable.buttons library to enable an Export to Excel feature. However, I encountered a limitation where only the first 10 rows on the current page are exported due to p ...

Personalize Badge Component

I've been on the hunt for a solution to customize a badge component similar to what's seen here: https://mui.com/material-ui/react-badge/. As of now, only options for making it a dot or adding a number in a circle are available. However, I' ...

Promise and Determination failing to produce results

const { GraphQLServer } = require('graphql-yoga'); const mongoose = require('mongoose'); mongoose.connect("mongodb://localhost/test1"); const Todo = mongoose.model('Todo',{ text: String, complete: Boolean }); const ...

Generating Placeholder Variables Within a v-for Iteration

Encountering a problem with Vue-JS involving v-for loops and v-model properties. I have an array of items: <input v-for="i in list" v-model="i.model" ... (other tags that use i) > </input> Accompanied by some JavaScr ...

Transform various tables enclosed in separate div elements into sortable and filterable tables

I'm encountering an issue with making multiple tables sortable and searchable on one page. Despite all the tables having the same class and ID, only the first table is responsive to sorting and searching. I've followed a tutorial that recommends ...

What is the reason for the new page rendering from the bottom of the screen in React?

Whenever I navigate between pages in my React project, the page always starts at the bottom instead of staying at the top after rendering. I am using router v5 and have been unable to find a solution specifically for this version. I have attempted differe ...

What is the best method for obtaining a modified image (img) source (src) on the server side?

Having some trouble with a concept in ASP.Net that's causing me quite the headache. I am fairly new to ASP.Net and struggling with something that seems much easier in PHP. I created an img element with an empty src attribute : <img runat="server" ...

Fluid Grid System with columns of specific dimensions

Recently delving into the world of Foundation Framework, I've just begun utilizing it for my projects. My current task involves crafting a responsive design with the help of the Foundation Grid system. Specifically, I've set up a grid layout for ...

Awesome method of redirecting outdated URLs to the most recent established URL

My website heavily relies on JavaScript and communicates with a .NET C# RPC service. We encountered an issue where clients' browsers cached the JavaScript, so we decided to add a version number to the URL in order to force them to use the latest JavaS ...

Having difficulty interpreting the JSON response from Laravel

Having trouble with headers? Here's an example in PHP: return response()->json([ 'somedata' => 1 ]); And in JS: $.get('/page', function(data) { console.log(data) }); Here's the result: HTTP/1.0 200 OK Cache-Control: ...

Employ a variable within the fetch method to retrieve JSON data

Currently, I am in the process of developing a system that extracts specific information from a JSON file based on user input. One challenge that I am facing is how to incorporate a variable into the designated section of my code; fetch( ...

Tips for resolving Vue.js static asset URLs in a production environment

I included the line background-image: url(/img/bg.svg); in my CSS file. During development mode, this resolves to src/img/bg.svg since the stylesheet is located at src/css/components/styles.css. However, when I switch to production mode, I encounter a 40 ...

RxJs will only consider the initial occurrence of a specific type of value and ignore any subsequent occurrences until a different type of value is encountered

I'm faced with a situation where I need to extract the first occurrence of a specific value type, followed by the next unique value of a different type. Let's break it down with an example: of(1,1,1,1,2,3,4) .pipe( // some operators ) .subsc ...

Is there a way to automatically restart my Gulp task when I save changes?

I have a series of Gulp tasks in version 4 that handle tasks like compiling Webpack and Sass, optimizing images, etc. These tasks are automated through a "watch" task while I am working on a project. However, when my watch task is active, saving a file tr ...

Discovering the frequency of a specific key in a JSON object or array using JavaScript

Suppose I have a JSON object with the given data, how can I determine the frequency of the key: "StateID"? [{"StateID":"42","State_name":"Badakhshan","CountryID":"1"}, {"StateID":"43","State_name":"Badgis","CountryID":"1"}, {"StateID":"44","State_name": ...

Is the Ajax response value consistently 1?

I am facing an issue where a JavaScript in an HTML page is sending two variables to a PHP script, which then echoes one of the variables at the end. However, the response value always remains 1. Despite trying methods like alerting, console.log, and puttin ...