[
{"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].l开发者_JS百科astName
}
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.
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);
}
}
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;
});
精彩评论