使用 Javascript 搜索 JSON

发布于 2024-11-03 04:54:43 字数 482 浏览 1 评论 0原文

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

上面是我的 JSON 数据,

  var searchBarInput = TextInput.value;

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

我收到了此警报。现在我有一个 TextInput,在输入时应该搜索 Json 并给出结果。我正在搜索姓氏值。

我如何获取 JSON 中的值并进行搜索。

  [
{"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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蝶…霜飞 2024-11-10 04:54:43

这是:

var searchBarInput = TextInput.value;

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

不正确的。迭代数组时应该做的是:

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

“for ... in”机制并不是真正用于迭代数组的索引属性。

现在,为了进行比较,您只需查找文本输入中的名称是否等于列表条目的“lastName”字段:

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

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);
  }
}
留一抹残留的笑 2024-11-10 04:54:43

您不应该使用 for..in 来迭代数组。相反,请使用普通的旧 for 循环。要获取与姓氏匹配的对象,请过滤数组。

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

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;
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文