Javascript 使用match()搜索数组中的多个值
我希望将对象作为其中一个值与搜索文本匹配的输出。我现在用return match做这个。但我还没有弄明白,如何测试数组中的数字。目前,它只在我输入类型或名称时起作用 例如,如果我输入2,它应该输出[{“type”:“ABe 8/12”,“name”:“ZTZ”,“number”:[“1”,“2”,“3”,“4”,“7”]}] Json文件:Javascript 使用match()搜索数组中的多个值,javascript,json,regex,match,Javascript,Json,Regex,Match,我希望将对象作为其中一个值与搜索文本匹配的输出。我现在用return match做这个。但我还没有弄明白,如何测试数组中的数字。目前,它只在我输入类型或名称时起作用 例如,如果我输入2,它应该输出[{“type”:“ABe 8/12”,“name”:“ZTZ”,“number”:[“1”,“2”,“3”,“4”,“7”]}] Json文件: [ {"type":"ABe 8/12", "name":"ZTZ"
[
{"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=等待取数('https://cmd-golem.github.io/json/test.json');
const resJson=wait res.json();
让matches=resJson.filter(数据=>{
const regex=new RegExp(`^${searchText}`,'gi');
返回data.type.match(regex)| | data.name.match(regex);
});
console.log(匹配项)
};
search.addEventListener('input',()=>searchData(search.value))代码>
我认为你的思路是对的。您可以使用以下内容搜索特定的引用文本:
let数据=[
{“类型”:“ABe 8/12”,“名称”:“ZTZ”,“编号”:[“1”、“2”、“3”、“4”、“7”],
{“类型”:“ABe 4/16”,“名称”:“STZ”,“数字”:[“5”、“6”、“8”、“9”、“12”],
{“类型”:“ABe 4/16”,“名称”:“RTZ”,“编号”:[“10”、“11”、“13”、“14”、“15”],
{“类型”:“测试”,“名称”:“RTZ”,“编号”:[“16”,“17”,“18”,“19”,“20”]}
];
让filter=“2”;
let pattern=newregexp(`${filter}`);
让filtered=data.filter((d)=>pattern.test(JSON.stringify(d));
console.log(过滤)代码>我的建议。见评论
const search=document.getElementById('search');
const searchData=async searchText=>{
const res=等待取数('https://cmd-golem.github.io/json/test.json');
const resJson=wait res.json();
const regex=new RegExp(`^${searchText}`,'gi');//注意它位于过滤器之外。
//递归。
const found=data=>(Array.isArray(data)?data.find(found):data.match(regex));
让matches=resJson.filter(data=>(found(data.type)| | found(data.name)| | found(data.number));
console.log(匹配项);
};
search.addEventListener('input',()=>searchData(search.value))代码>
包括或some@epascarello那么如何在现有代码中实现include呢?请注意,只有当stringify返回包含整个对象的字符串时,才会起作用,例如,任何嵌套的自定义对象都将被排除在外。如果您还需要搜索这些内容,则需要更彻底的搜索机制,如SMAKSS建议的那样。