我想比较两种不同React状态下的对象数组。我的状态值如下所示:
review1 = [{name: John, Title: Manager},{name: Peter, Title: Engineer}, {name: Serena, Title: Supervisor}]
review2 = [{personName: John, ismanager: yes}, {name: Peter, ismanager: no}, {personName: Serena, ismanager: yes},{personName: John, ismanager:yes}]
现在,我想统计一下担任经理的人。如果是倍数,则计数应增加。在这种情况下,约翰是两个职位的经理,然后计数约翰为2以及彼得0和塞雷娜1
我正在尝试使用以下功能,但无法正常工作。
let filter = this.state.review1.map(elem=>elem.personName)
count = this.state.review2.map(data=> data.name).reduce((n,x) =>n +(x === filter.personName && data.ismanager === "yes"),null)
<div> John: {ismanger.count}, Serena: {ismanager.count}, Peter: {ismanager.count} </div>
答案 0 :(得分:2)
您可以直接将经理与条件联系起来。
var review2 = [{ personName: 'John', ismanager: 'yes' }, { personName: 'Peter', ismanager: 'no' }, { personName: 'Serena', ismanager: 'yes' }, { personName: 'John', ismanager: 'yes' }],
count = Array.from(
review2.reduce((m, { personName, ismanager }) => m.set(personName, (m.get(personName) || 0) + (ismanager === 'yes')), new Map),
([name, count]) => ({ name, count })
);
console.log(count);
答案 1 :(得分:0)
我想我们只需要在review2
数组上做对吧?
试试这个。
演示于:playcode
review2 = [{personName: 'John', ismanager: 'yes'}, {name: 'Peter', ismanager: 'no'}, {personName: 'Serena', ismanager: 'yes'},{personName: 'John', ismanager:'yes'}]
const countMap = review2.reduce((accum, person) => {
const isPersonName = !!person.personName;
const name = isPersonName ? person.personName : person.name;
if (accum[name] && person.ismanager === 'yes') {
accum[name]++;
} else if (person.ismanager === 'yes') {
accum[name] = 1;
}
return accum;
}, {})
console.log(countMap);