3 回答
TA贡献1841条经验 获得超3个赞
您可以使用Array#somewith 来Array#includes检查一个数组是否包含另一个数组的任何元素。
const testeArray = [{name:"antonio", category: ["One","Two"]},{name:"joana", category: ["Two"]}];
const catArray1 = ["One","Two"];
const catArray2 = ["One"];
const text = "an"
const resultArray1 = testeArray.filter((item)=>{
return item.name.includes(text) && item.category.some(x => catArray1.includes(x));
})
console.log(resultArray1); //should return antonio and joana objects
const resultArray2 = testeArray.filter((item)=>{
return item.name.includes(text) && item.category.some(x => catArray2.includes(x));
})
console.log(resultArray2); //should return antonio object only
TA贡献1869条经验 获得超4个赞
如果您正在寻找精确匹配,可以使用JSON.stringify将数组转换为字符串并使用===运算符进行匹配。
const testeArray = [{name:"antonio", category: ["One","Two"]},{name:"joana", category: ["Two"]}];
const catArray1 = ["One","Two"];
const catArray2 = ["One"];
const text = "an"
const resultArray1 = testeArray.filter((item)=>{
return item.name.includes(text) && JSON.stringify(item.category) === JSON.stringify(catArray1);
})
console.log(resultArray1); //should return antonio and joana objects
const resultArray2 = testeArray.filter((item)=>{
return item.name.includes(text) && JSON.stringify(item.category) === JSON.stringify(catArray2);
})
console.log(resultArray2);
当两个数组的元素位于相同位置时,这将起作用。
TA贡献1847条经验 获得超7个赞
您可以过滤项目类别并检查返回的数组长度是否大于0。
<html>
<script>
const testeArray = [{name:"antonio", category: ["One","Two"]},{name:"joana", category: ["Two"]}];
const catArray1 = ["One","Two"];
const catArray2 = ["One"];
const text = "an"
const resultArray1 = testeArray.filter((item)=>{
return item.name.includes(text) && item.category.filter(cat => catArray1.indexOf(cat) > -1).length > 0;
})
console.log(resultArray1); //should return antonio and joana objects
const resultArray2 = testeArray.filter((item)=>{
return item.name.includes(text) && item.category.filter(cat => catArray2.indexOf(cat) > -1).length > 0;
})
console.log(resultArray2); //should return antonio object only
</script>
</html>
添加回答
举报