简体   繁体   English

使用javascript通过字符串过滤json的字段

[英]filtering a field of json by a string with javascript

I am trying to filter a json field by a string with javascript. 我正在尝试用javascript字符串过滤json字段。 More clearly, I have a search box, and a fake return json. 更清楚的是,我有一个搜索框和一个假的return json。 When I press some letters in the input box, an ajax call should filter my fake response according to the input string, thus I can show the result. 当我在输入框中按一些字母时,ajax调用应根据输入字符串过滤我的虚假响应,这样我就可以显示结果。

My input box and call function with my fake ajax response is working fine. 我的输入框和带有虚假ajax响应的调用函数运行正常。 But I have trouble with filtering it. 但是我在过滤它时遇到了麻烦。

var res = response.filter(function (i, n) {
    return String(n.Name).toLowerCase().indexOf(String(srt).toLowerCase()) === 0;
});

Here is my fake JSON response: 这是我的虚假JSON响应:

[{ "Name": "ALICE", "Close": 7.12, "UpDown": 1 }, { "Name": "MICHAEL", "Close": 110.78, "UpDown": 1 }]

n.Name returns undefined . n.Name返回undefined So, the res becomes an object with undefined 's. 因此, res成为具有undefined的对象。 In this case, if I enter und for example, all of the elements are shown; 在这种情况下,例如,如果我输入und ,则显示所有元素; if I enter something else, none of the elements can pass the filter. 如果我输入其他内容,则所有元素都无法通过过滤器。

Why is this happening and how can I fix this problem? 为什么会发生这种情况,如何解决此问题?

You have the .filter syntax mixed up. 您混淆了.filter语法。 You can check it out here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter 您可以在这里查看: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

The first argument is the value, while the second is the index. 第一个参数是值,第二个参数是索引。 What ends up happening with your code is that you're trying to find the Name property of the index 0, which is causing your undefined error. 代码最终发生的事情是,您试图找到索引0的Name属性,这导致了undefined错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM