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

Above is my JSON Data

  var searchBarInput = TextInput.value;

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

I am getting the alert for this. Now i have a TextInput which on typing should search the Json and yield me the result. I am searching for lastname value.

How would i take the value and search in my JSON.

2 Answers 2

3

This:

var searchBarInput = TextInput.value;

for (i in recentPatientsList.length) {
 alert(recentPatientsList[i].lastName); // added the ) for you
}

is incorrect. What you should do to iterate over an array is:

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

The "for ... in" mechanism isn't really for iterating over the indexed properties of an array.

Now, to make a comparison, you'd just look for the name in the text input to be equal to the "lastName" field of a list entry:

for (var i = 0; i < recentPatientsList.length; ++i) {
  if (searchBarInput === recentPatientsList[i].lastName) {
    alert("Found at index " + i);
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Will the alert yield me only the results which equal the last name.. to print those data should i use alert(recentPatientsList[i].lastName after the comparision.
The "alert()" is just there as an example. The point is that all you have to do is a simple comparison between the input value and the strings in your table; there's nothing magical about it.
"The "for ... in" mechanism isn't really for iterating over the indexed properties of an array." Although it's very useful for avoiding unnecessary loop iterations on sparse arrays. The OP's array isn't sparse, so simple loops are the best answer. For sparse arrays, for..in is the best answer but you must use if (recentPatientList.hasOwnProperty(i) && String(Number(i)) === i) to be sure you're sticking to just the entries in the array.
1

You should not use for..in to iterate over an array. Instead use a plain old for loop for that. To get objects matching the last name, filter the array.

var matchingPatients = recentPatientsList.filter(function(patient) {
    return patient.lastName == searchBarInput;
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.