使用JavaScript在JSON中搜索字符

时间:2011-04-23 21:09:14

标签: javascript json

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

将我的输入与JSON进行比较。

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

通过这个我能够看到我是否将我的输入与JSON匹配。如何获得姓氏以“N”开头或给定输入的数据结果。

1 个答案:

答案 0 :(得分:1)

假设您的searchBarInput等于"n"试试这个:

var results = []; // initialize array of results
for (var i = 0; i < recentPatientsList.length; ++i) {
  if (recentPatientsList[i].lastName.indexOf(searchBarInput) == 0) {
    results.push(recentPatientsList[i].lastName);
  }
}
alert('Results: ' + results.toString());