[英]How to filter array of objects with nested arrays of objects based on other arrays
[英]How to filter array of objects with nested arrays based on other arrays
我有一個對象數組。 我想過濾以僅包含測試 arrays 中的所有元素都存在於原始數組中的對象。
示例代碼。
const cards = [
{
id: "1",
name: "J",
tag: ["red", "yellow", "blue", "white"],
size: ["small", "medium"],
},
{
id: "2",
name: "S",
tag: ["red", "green", "black"],
size: ["small", "medium"],
},
{
id: "3",
name: "K",
tag: ["green", "purple", "brown", "white"],
size: ["large"],
}
測試 arrays
const sizeArray = ["medium", "small"];
const tagArray = ["red", "black"];
我希望過濾后的數組只包含第二個 object。
我已經嘗試過使用過濾器,包含並且沒有運氣查看類似問題的許多其他答案。
非常感謝。
我猜這可能是你需要的:
const cards = [
{
id: "1",
name: "J",
tag: ["red", "yellow", "blue", "white"],
size: ["small", "medium"],
},
{
id: "2",
name: "S",
tag: ["red", "green", "black"],
size: ["small", "medium"],
},
{
id: "3",
name: "K",
tag: ["green", "purple", "brown", "white"],
size: ["large"],
}
];
const sizeArray = ["medium", "small"];
const tagArray = ["red", "black"];
// filtering the cards array
const filltered = cards.filter(ch => {
// according have every size in sizeArray and
// every tag in tagsArray
return sizeArray.every(size => ch.size.includes(size))
&& tagArray.every(tag => ch.tag.includes(tag));
});
console.log(filltered);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.