如何使用两个字符串(搜索框)动态过滤数组值?这是我到目前为止所尝试过的:
if (!!this.searchCompany.toLowerCase() || !!this.searchName.toLowerCase()) {
this.filter = true
this.newval = this.list.filter(post => {
if (!!this.searchCompany.toLowerCase()) {
return post.profile.company ? post.profile.company.toLowerCase().includes(this.searchCompany.toLowerCase()) : null
} else if (!!this.searchName.toLowerCase()) {
return post.profile.full_name.toLowerCase().includes(this.searchName.toLowerCase())
} else {
return post
}
})
this.searchCompany 和 this.searchName 是我表单中的搜索框。
this.list的数组内容
最佳答案
更新:
这是您的状况检查
if(!!this.searchCompany.toLowerCase())
它不检查值是否存在且是否为小写。首先通过String方法将其转换为小写,然后转换为boolean类型。我们知道,空字符串会转换为 bool 值 FALSE,任何非空字符串都会转换为 TRUE。此外,如果this
中没有出现searchCompany
属性,您可能会收到TypeError。
这里是如何在对象数组中搜索的小示例片段
const posts = [{
company: 'Coca-Cola',
name: 'Rocket'
},
{
company: 'Pepsi-Cola',
name: 'Groot'
}
]
let form = document.forms['search-form']
let resultBox = document.querySelector('#result-box')
let searchButton = document.querySelector('#search')
searchButton.addEventListener('click', doSearch, false)
function searchPost(parameter, searchString) {
return posts.find(post => post[parameter].toLowerCase().includes(searchString.toLowerCase()))
}
function isFormEmpty() {
return [...form.children].filter(e => e.type === 'text').reduce((r, c) => r && !c.value.length, true)
}
function doSearch() {
if (isFormEmpty(form)) {
e.preventDefault()
return false
}
let searchNameEl = form.querySelector('[name="searchName"]')
let searchCompanyEl = form.querySelector('[name="searchCompany"]')
let searchParam = searchCompanyEl.value.length ? 'company' : 'name'
let searchText = searchCompanyEl.value.length ? searchCompanyEl.value : searchNameEl.value
let post = searchPost(searchParam, searchText)
resultBox.textContent = JSON.stringify(post)
}
form {
display: block;
}
.result {
margin-top: 10px;
}
<form id="search-form">
<label>Search company</label>
<input type="text" name="searchCompany" />
<label>Search name</label>
<input type="text" name="searchName" />
<button type="button" id="search">Search</button>
</form>
<div class="result">
<pre id="result-box"></pre>
</div>
关于Javascript数组过滤两个搜索框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56880083/