【发布时间】:2020-10-25 05:51:14
【问题描述】:
我需要通过提交表单过滤对象。现在过滤时,我会收到每个过滤器的对象数组。我需要其他场景,在检查一种过滤器类型后,例如“大小”(一个或多个),然后检查“生产者”,它应该返回只检查大小的对象。例子: 检查 275-290,然后检查“polytech”,它返回 3 个对象而不是 1 个,同时具有两个参数。
let data = [
{ id: 1, producer: ["polytech"], size: ["275-290"] },
{ id: 2, producer: ["polytech"], size: ["325-350"] },
{ id: 3, producer: ["allergan"], size: ["275-290"] },
{ id: 4, producer: ["motiva"], size: ["325-350"] },
{ id: 5, producer: ["motiva"], size: ["355-370"] },
]
let filteredOutput = ""
const form = document.querySelector("form")
form.addEventListener("submit", (e) => {
const inputs = form.querySelectorAll("input")
let name = ""
let value = ""
let postArray = []
data.forEach((post) => {
inputs.forEach((input) => {
if (input.checked) {
name = input.name
value = input.value
if (post[name].includes(value)) {
postArray.push(post)
}
}
})
})
const allposts = new Set(postArray)
filteredOutput = [...allposts]
console.log(filteredOutput)
console.log(filteredOutput.length)
e.preventDefault()
})
<form>
<div class="faq-body filter_buttons">
<input type="checkbox" name="producer" value="allergan" id="allergan" />
<label for="allergan">allergan</label>
<input type="checkbox" name="producer" value="polytech" id="polytech" />
<label for="polytech">polytech</label>
<input type="checkbox" name="producer" value="motiva" id="motiva" />
<label for="motiva">motiva</label>
</div>
<div class="faq-body filter_buttons">
<input type="checkbox" name="size" value="275-290" id="275-290" />
<label for="275-290">275-290</label>
<input type="checkbox" name="size" value="295-320" id="295-320" />
<label for="295-320">295-320</label>
<input type="checkbox" name="size" value="325-350" id="325-350" />
<label for="325-350">325-350</label>
<input type="checkbox" name="size" value="355-370" id="355-370" />
<label for="355-370">355-370</label>
</div>
<input type="submit" value="Submit" />
</form>
【问题讨论】:
标签: javascript arrays sorting filter