我有这个数组:
[{
"id": "5b221edea8abbc4194a62b90",
"name": "Job one",
"tasks": [{
"id": "5b221edea8abbc4194a62b91",
"name": "Task 2",
"status": "finished",
},
{
"id": "5b221edea8abbc4194a62b91",
"name": "Task 3",
"status": "pending",
},
{
"id": "5b221edea8abbc4194a62b91",
"name": "Task 3",
"status": "to_do",
},
]
},
{
"id": "5b221edea8abbc4194a62b91",
"name": "Job two",
"tasks": [{
"id": "5b221edea8abbc4194a62b96",
"name": "Task 5",
"status": "finished",
},
{
"id": "5b221edea8abbc4194a62b97",
"name": "Task 8",
"status": "accepted",
},
]
},
]
所有任务都是进度条的100%。在这种情况下有5个任务。 100%= 5个任务。
我想知道进度条的百分比,根据任务是否具有“已完成”状态。在这种情况下,应该是(100 x 2):5 = 40%在进度条中完成。
谢谢!
答案 0 :(得分:0)
您只需使用嵌套的forEach
来计算百分比。
尝试以下方法:
var arr = [{"id":"5b221edea8abbc4194a62b90","name":"Job one","tasks":[{"id":"5b221edea8abbc4194a62b91","name":"Task 2","status":"finished"},{"id":"5b221edea8abbc4194a62b91","name":"Task 3","status":"pending"},{"id":"5b221edea8abbc4194a62b91","name":"Task 3","status":"to_do"}]},{"id":"5b221edea8abbc4194a62b91","name":"Job two","tasks":[{"id":"5b221edea8abbc4194a62b96","name":"Task 5","status":"finished"},{"id":"5b221edea8abbc4194a62b97","name":"Task 8","status":"accepted"}]}];
var completedCount = 0;
var total = 0;
arr.forEach((o)=>{
o.tasks.forEach((task) => {
if(task.status == "finished")
completedCount++;
total++;
});
});
var percentage = (completedCount/total)*100;
console.log(percentage+"%");

答案 1 :(得分:0)
您可以使用concat
和map
展平数组。使用reduce
获取感知。
let arr = [{"id":"5b221edea8abbc4194a62b90","name":"Job one","tasks":[{"id":"5b221edea8abbc4194a62b91","name":"Task 2","status":"finished"},{"id":"5b221edea8abbc4194a62b91","name":"Task 3","status":"pending"},{"id":"5b221edea8abbc4194a62b91","name":"Task 3","status":"to_do"}]},{"id":"5b221edea8abbc4194a62b91","name":"Job two","tasks":[{"id":"5b221edea8abbc4194a62b96","name":"Task 5","status":"finished"},{"id":"5b221edea8abbc4194a62b97","name":"Task 8","status":"accepted"}]}]
let result = [].concat(...arr.map(o => o.tasks)).reduce((c, {status}) => {
if (status === "finished") c.finished++;
c.total++;
c.percentage = (c.finished / c.total) * 100;
return c;
}, {finished: 0,total: 0,percentage: 0})
console.log(result);