简体   繁体   English

如何比较处于两种不同React状态的数组对象

[英]How to compare array objects present in two different React states

I want to compare object arrays present in two different React states. 我想比较两种不同的React状态中存在的对象数组。 My state values are something like below: 我的状态值如下所示:

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}]

Now I want to get count of people who are manager. 现在,我想统计一下担任经理的人。 If multiple then count should increase. 如果是倍数,则计数应增加。 In this case John is manager for two position then count for John is 2 and for Peter 0 and Serena 1 在这种情况下,约翰是两个职位的经理,然后计数约翰为2,彼得0和小威1

I am trying below function but it doesn't work as expected. 我正在尝试下面的功能,但不能按预期工作。

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> 

You could count directly the manager with the condition. 您可以直接将条件与经理联系起来。

 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); 

I guess we only need to do it over review2 array right? 我想我们只需要在review2数组上做对吧? Try this. 尝试这个。

Demo At: playcode 演示于: 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM