我的对象数组在下面
var filterStatus = [{ doc_count: 49, key: "Completed", color: "#1DC9B7" }, { doc_count: 147, key: "Failed", color: "#F14C69" }, { doc_count: 321, key: "In Progress", color: "#FFC568" }, { doc_count: 29, key: "Started" }];
我想获取包含“已完成”,“失败”和“进行中(应包含开始)”状态的结果
我正在尝试使用以下代码
var result = filterStatus.filter(obj => { if(obj.key == 'Started' || obj.key == 'In Progress'){ return obj}} ).map(obj => obj.doc_count).reduce((p, c) => p + c, 0);
我得到结果350
我的预期输出是
[{ doc_count: 49, key: "Completed", color: "#1DC9B7" }, { doc_count: 147, key: "Failed", color: "#F14C69" }, { doc_count: 350, key: "In Progress", color: "#FFC568" }];
注意::预期输出包含In Progress doc_count中的Started和In Progress。
答案 0 :(得分:1)
分别使用reduce和map
var filterStatus = [{
doc_count: 49,
key: "Completed",
color: "#1DC9B7"
}, {
doc_count: 147,
key: "Failed",
color: "#F14C69"
}, {
doc_count: 321,
key: "In Progress",
color: "#FFC568"
}, {
doc_count: 29,
key: "Started"
}];
var val=filterStatus.map(function(e){
if(e.key=="In Progress" || e.key=="Started")
return e.doc_count
else
return 0}).reduce(function(acc,e){return acc+=e},0)
var result = filterStatus.filter(function(obj) {
if(obj.key == 'In Progress')
obj.doc_count=val;
if (obj.key == 'Completed' || obj.key == 'In Progress' || obj.key == 'Failed')
return obj;
})
console.log(result)
答案 1 :(得分:1)
const filterStatus = [{ doc_count: 49, key: "Completed", color: "#1DC9B7" }, { doc_count: 147, key: "Failed", color: "#F14C69" }, { doc_count: 321, key: "In Progress", color: "#FFC568" }, { doc_count: 29, key: "Started" }];
// filter out "Started"
const result = filterStatus.filter(({key}) => key !== "Started");
// find and update "In Progress"
result.find(({key}) => key === "In Progress").doc_count += filterStatus.find(({key}) => key === "Started").doc_count;
console.log(result)
答案 2 :(得分:-1)
var filterStatus = [{ doc_count: 49, key: "Completed", color: "#1DC9B7" }, { doc_count: 147, key: "Failed", color: "#F14C69" }, { doc_count: 321, key: "In Progress", color: "#FFC568" }, { doc_count: 29, key: "Started" }];
function mergeInProgressStarted () {
return filterStatus.filter(({key}) => {
return ['In Progress', 'Started'].indexOf(key) > -1;
}).reduce((acc, status) => {
acc.doc_count += status.doc_count;
if (status.color) {
acc.color = status.color;
}
return acc;
}, { key: "In Progress", doc_count: 0 })
}
filterStatus.filter(({ key }) => ['Completed', 'Failed'].indexOf(key) > -1).concat([mergeInProgressStarted()])