2 回答

TA貢獻2019條經驗 獲得超9個贊
使用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")))

TA貢獻1785條經驗 獲得超4個贊
我覺得你的問題真的很難理解。如果你只想要 @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()
已經返回了一個新數組。
添加回答
舉報