![](/img/trans.png)
[英]How to filter an array of objects (with arrays inside) with another array of objects
[英]Filter on arrays on Objects inside array of Objects in JavaScript
我想按類別獲取 Main 的數組
[
{
"@id": "/api/main/7648",
"@type": "Main",
category: [{
name: "laboriosam"
}]
},
{
"@id": "/api/main/7647",
"@type": "Main",
category: [{
name: "foo"
},
{
name: "bar"
}
]
}
]
所以我嘗試:
console.log([...this.state.mains].filter(main => main.category.filter(category => category.name == "foo")))
但它返回了我的一切,我不明白為什么?
使用Array.prototype.some
,您可以決定該值是否存在。
使用Array.filter
函數,它僅過濾true
值,因此需要在回調時返回布爾值。
const input = [{ "@id": "/api/main/7648", "@type": "Main", category: [{ name: "laboriosam" }] }, { "@id": "/api/main/7647", "@type": "Main", category: [{ name: "foo" }, { name: "bar" } ] } ]; console.log(input.filter(main => main.category.some(category => category.name == "foo")))
我覺得你的問題真的很難理解。 如果你只想要@type = "Main" 的對象,你可以這樣做
this.state.mains.filter(x => x["@type"] === "Main");
如果您想過濾掉那些沒有特定類別的人,您可以添加另一個過濾器,如下所示:
this.state.mains
.filter(x => x["@type"] === "Main")
.filter(x => x.category.findIndex(c => c.name === "foo") !== -1);
顯然,在大數組的情況下,您還將兩個檢查都放入一個過濾器中,但這可能不那么可讀。
還要注意[...this.state.mains].filter(...)
是多余的,因為.filter()
已經返回一個新數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.