【发布时间】:2021-01-19 14:35:20
【问题描述】:
我想获取对象作为输出,其中一个值与搜索的文本匹配。我目前使用返回匹配来执行此操作。但我还没有弄清楚,如何测试数组中的数字。目前它只有在我输入类型或名称时才有效。
例如如果我输入 2 它应该输出 [{"type":"ABe 8/12", "name":"ZTZ","numbers":["1", "2", "3", "4", "7"]}]
Json 文件:
[
{"type":"ABe 8/12", "name":"ZTZ","numbers":["1", "2", "3", "4", "7"]},
{"type":"ABe 4/16", "name":"STZ","numbers":["5", "6", "8", "9", "12"]},
{"type":"ABe 4/16", "name":"RTZ", "numbers":["10", "11", "13", "14", "15"]},
{"type":"Test", "name":"RTZ", "numbers":["16", "17", "18", "19", "20"]}
]
Javascript:
const search = document.getElementById('search');
const searchData = async searchText => {
const res = await fetch('https://cmd-golem.github.io/json/test.json');
const resJson = await res.json();
let matches = resJson.filter(data => {
const regex = new RegExp(`^${searchText}`, 'gi');
return data.type.match(regex) || data.name.match(regex);
});
console.log(matches)
};
search.addEventListener('input', () => searchData(search.value));
有人知道如何通过返回匹配来做到这一点,或者如果用其他方式不可能做到这一点。
const search = document.getElementById('search');
const searchData = async searchText => {
const res = await fetch('https://cmd-golem.github.io/json/test.json');
const resJson = await res.json();
let matches = resJson.filter(data => {
const regex = new RegExp(`^${searchText}`, 'gi');
return data.type.match(regex) || data.name.match(regex);
});
console.log(matches)
};
search.addEventListener('input', () => searchData(search.value));
<input id="search" type="text" placeholder="Search">
【问题讨论】:
-
包括或一些
-
@epascarello 我如何在现有代码中实现包含?
标签: javascript json regex match