Javascript数组过滤器两个搜索框

时间:2019-07-04 02:53:27

标签: javascript arrays filter include tostring

如何使用两个字符串(搜索框)动态过滤数组值?到目前为止,这是我尝试过的:

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 是我表单中的搜索框。

此列表

的数组内容

enter image description here

1 个答案:

答案 0 :(得分:0)

UPD:

这是您的病情检查

if(!!this.searchCompany.toLowerCase())

它不检查该值是否显示和小写。首先,它将通过String方法转换为小写,然后转换为 boolean 类型。我们知道,空字符串将强制转换为布尔值 FALSE ,而任何非空字符串将强制转换为 TRUE 。此外,如果searchCompany中没有显示this属性,则可以得到 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>