简体   繁体   中英

filtering a field of json by a string with javascript

I am trying to filter a json field by a string with javascript. More clearly, I have a search box, and a fake 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.

My input box and call function with my fake ajax response is working fine. 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:

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

n.Name returns undefined . So, the res becomes an object with undefined 's. In this case, if I enter und for example, all of the elements are shown; 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. You can check it out here: https://developer.mozilla.org/en-US/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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