这个问题已经在这里有了答案: > How to filter object array based on attributes? 11个
我正在尝试遍历包含任务对象数组的对象.我将如何遍历每个键值对,例如返回状态为“已完成”的所有任务.
{
"quests": [
{
"title": "A Rum Deal",
"status": "COMPLETED",
"difficulty": 2,
"members": true,
"questPoints": 2,
"userEligible": true
}
],
"loggedIn": false
}
解决方法:
要进行迭代,您可以使用Array#forEach
object.quests.forEach(function (a) {
if (a.status === "COMPLETED") {
// do something with the data
}
});
要返回已完成任务的选择,可以使用Array#filter
var completed = object.quests.filter(function (a) {
return a.status === "COMPLETED";
});