如何从使用javascript的数组中获得按优先级的票的总和



我有以下数组

{
agent_id:001,
priority:"High",
task_id:T1
},
{
agent_id:001,
priority:"High",
task_id:T1
},
{
agent_id:001,
priority:"Medium",
task_id:T1
}
{
agent_id:002,
priority:"High",
task_id:T1
}

我需要得到上述数组的如下输出:

{agent_id:001,High_Count:2,Medium_Count:1},
{agent_id:002,High_Count:1,Medium_Count:0}
下面是我的代码:

for (let I = 0;我& lt;dataModel.ticketList.length;我+ +){var priority = JSON.stringify(datmodel . ticketlist [i].Priority);

if (!map.has(priority)) 
{
map.set(priority, {
Agent: dataModel.ticketList[i].Agent,
Low: 1,
});
} 
else 
{
map.get(priority).Low++;
}
}

const res = Array.from(map.values())返回res;

您可以这样使用Array.prototype.reduce:

const data = [
{ agent_id: 001, priority: "High", task_id: "T1" },
{ agent_id: 001, priority: "High", task_id: "T1" },
{ agent_id: 001, priority: "Medium", task_id: "T1" },
{ agent_id: 002, priority: "High", task_id: "T1" },
];
const result = data.reduce((acc, cur) => {
const index = acc.findIndex((x) => x.agent_id === cur.agent_id);
if (~index) {
const value = acc[index][`${cur.priority}_Count`] || 0;
acc.splice(index, 1, {
...acc[index],
[`${cur.priority}_Count`]: value + 1,
});
} else {
acc.push({ agent_id: cur.agent_id, [`${cur.priority}_Count`]: 1 });
}
return acc;
}, []);
console.log(result);

请使用Array.reduce()函数

const data = [{ agent_id:001, priority:"High", task_id:"T1" }, { agent_id:001, priority:"High", task_id:"T1" }, { agent_id:001, priority:"Medium", task_id:"T1" }, { agent_id:002, priority:"High", task_id:"T1" }];
const urgent = "Urgent";
let result = data.reduce((total, item) => {
if(total.map(val => val.agent_id).includes(item.agent_id)) {
const index = total.map(val => val.agent_id).indexOf(item.agent_id);
if(total[index].hasOwnProperty(item.priority + "_Count"))
total[index][item.priority + "_Count"] ++;
else
total[index][item.priority + "_Count"] = 1;
} else {
let obj = {agent_id: item.agent_id};
let priorities = data.map(val => val.priority).filter((val, i, self) => self.indexOf(val) === i);
if(!!urgent) priorities.push(urgent);
priorities.forEach(val => {obj[val + "_Count"] = 0});
obj[item.priority + "_Count"] = 1;
total.push(obj);
}
return total;
},[]);
result = result.map(val => {
const total = Object.keys(val).reduce((total, key) => key === 'agent_id' ? total : total + val[key], 0);
return {...val, total: total};
});
console.log(result);

相关内容

最新更新