3 回答
TA贡献1831条经验 获得超10个赞
您可以尝试使用find()和includes()对象的 name 属性,最后使用filter().
演示:
var list = [
{
name:'aa',
searchWords:['aa','ab','bc']
},
{
name:'bb',
searchWords:['bb','bc','de']
}
]
document.getElementById('searchWord').addEventListener('input', function(){
console.clear();
var filterItems = list.find(item => item.name.includes(this.value));
filterItems = filterItems ? filterItems.searchWords : [];
filterItems = filterItems.filter(i => i.includes(this.value));
console.log(filterItems);
});
<input id="searchWord"/>
TA贡献2016条经验 获得超9个赞
您需要遍历 searchWords 数组以查找它是否与搜索词匹配。这个会工作
const filterItems = list.filter(
(item) => item.searchWords.filter((myWord) => myWord.indexOf(searchWord)>-1)
);
TA贡献1820条经验 获得超9个赞
代码的问题在于,当您使用 indexOf 时,它会尝试查找数组是否包含单词。例如:当您搜索 'a' 时,代码会检查数组中是否有任何单词 'a' 而不是任何包含字母 'a' 的单词。
您需要将 JS 部分更改为:
JS
const list = [{
name: 'aa',
searchWords: ['aa', 'ab', 'bc']
},
{
name: 'bb',
searchWords: ['bb', 'bc', 'de']
}
];
let searchWord = "a";
const filterItems = list.filter(
(item) => item.searchWords.filter(word => word.includes(searchWord)).length > 0
);
document.getElementById('result').innerHTML = JSON.stringify(filterItems);
<p id="result">
</>
添加回答
举报