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>
添加回答
舉報