提问人:learntocode2468 提问时间:6/18/2023 最后编辑:David Thomaslearntocode2468 更新时间:6/18/2023 访问量:28
使用 JavaScript 根据 Array 对象中的出现次数计算值
count the values based on number of occurrences in the array object using javascript
问:
我有对象数组,使用 JavaScript 计算状态
如果对象仅启动/仅进度/已启动、进度/已启动或进度已完成、已取消的组合 被视为started_progress计数
如果对象已完成,则仅视为已完成计数
如果对象已取消,则仅视为已取消的计数
如果对象已完成,则一起取消仅视为已完成计数
我试过:
var arrobj = [{
id: 22,
details: [{
status: "started"
},
{
status: "cancelled"
}
]
},
{
id: 24,
details: [{
status: "completed"
},
{
status: "cancelled"
}
]
},
{
id: 44,
details: [{
status: "progress"
}]
},
{
id: 54,
details: [{
status: "progress"
},
{
status: "completed"
}
]
},
{
id: 64,
details: [{
status: "cancelled"
}]
},
{
id: 74,
details: [{
status: "completed"
}]
}
];
var started_progress = arrobj.details.filter(e => ["started", "progress"].includes(e.status)).length;
var completed = arrobj.details.every(i => i.status === "completed").length;
var cancelled = arrobj.details.every(i => i.status === "cancelled").length;
预期输出
started_progress = 3
completed = 2
cancelled = 1
答:
0赞
James
6/18/2023
#1
下面有一种将数组简化为包含各种计数的对象的方法。如果逻辑不太正确,您可能需要调整大块。if
var arrobj =[
{id: 22, details:
[
{status: "started"},
{status: "cancelled"}
]
},
{id: 24, details:
[
{status: "completed"},
{status: "cancelled"}
]
},
{ id: 44, details:
[
{status: "progress"}
]
},
{ id: 54, details:
[
{status: "progress"},
{status: "completed"}
]
},
{ id: 64, details:
[
{status: "cancelled"}
]
},
{ id: 74, details:
[
{status: "completed"}
]
}
]
const output = arrobj.reduce((acc, el) => {
if (el.details.length === 1 && el.details[0].status === "cancelled") {
// only contains "cancelled"
acc.cancelled++;
} else if (el.details.length === 1 && el.details[0].status === "completed") {
// only contains "completed"
acc.completed++;
} else if (el.details.length === 2 && el.details.find(d => d.status === "cancelled") && el.details.find(d => d.status === "completed")) {
// only contains "completed" and "cancelled"
acc.completed++;
} else if (el.details.find(d => d.status === "progress" || d.status === "started")) {
// contains "progress" or "started"
acc.started_progress++;
}
return acc;
}, {
started_progress: 0,
completed: 0,
cancelled: 0
});
console.log(output);
评论
.filter()
.every()
arrobj.details is undefined