【问题标题】:Iterate through an Array of Objects and calculate occurrences of certain values遍历对象数组并计算某些值的出现
【发布时间】:2021-08-11 16:46:50
【问题描述】:

在我的 Vue/Nuxt 应用程序中,我有一个数组,其中包含多个对象(见下文)。

"Members" : [ {
    "Country" : "Spain",
    "Vote" : "For"
  }, {
    "Country" : "Italy",
    "Vote" : "For"
  },
  {
    "Country" : "Italy",
    "Vote" : "For"
  }, {
    "Country" : "Italy",
    "Vote" : "Against"
  }]

“国家/地区”值可以重复,“投票”值也可以重复。 我想要的是具有唯一国家/地区列表的新对象数组,计算“支持”和“反对”值的总数

例如,在上面的示例中,我需要一个如下所示的数组:

[{
   "Country" : "Spain",
   "VoteFor": 1,
   "VoteAgainst": 0
},

{
   "Country": "Italy",
   "VoteFor": 2,
   "VoteAgainst": 1
}]

我能够使用 Set() 对象获得唯一的国家/地区列表。

Members.forEach((Member) => {
        countrySet.add(Member.Country)
      })

但是,我不知道如何从那里继续。 任何帮助表示赞赏!

【问题讨论】:

  • 您对此进行了多深入的研究?你有没有发现这个可能? stackoverflow.com/questions/15360256/…你将如何尝试超越你的终点?你熟悉reduce吗?
  • 我在这个问题上花了大约 2 小时,但我的 JS 不是很高级,所以我有时会在基础方面苦苦挣扎。但是,Ori 的建议有效

标签: javascript arrays loops object


【解决方案1】:

const members = [ 
  { "Country" : "Spain", "Vote" : "For" }, 
  { "Country" : "Italy", "Vote" : "For" },
  { "Country" : "Italy", "Vote" : "For" }, 
  { "Country" : "Italy", "Vote" : "Against" }
];

const res = [...
// iterate over members while updating a map of Country-Member pairs
members.reduce((membersMap, { Country, Vote }) => {
  // get member from map
  const member = membersMap.get(Country);
  // if it doesn't exist, add with initial Vote
  if(!member) membersMap.set(Country, {Country, [Vote]:1});
  // else update the vote count of the current category
  else member[Vote] = (member[Vote] || 0) + 1; 
  return membersMap;
}, new Map)
// return all the values of this map, i.e., the members objects with the counts
.values()];

console.log(res);

【讨论】:

    【解决方案2】:

    将数组简化为 Map。如果地图中不存在Country,请为该国家/地区设置一个新对象。增加对象中的相关Vote。在 Map 的 .values() 迭代器上使用 Array.from() 将 Map 转换为数组。

    如果您只有ForAgain(弃权不是一个选项),您可以将if...else 转换为更简单的三元组。

    const members = [{"Country":"Spain","Vote":"For"},{"Country":"Italy","Vote":"For"},{"Country":"Italy","Vote":"For"},{"Country":"Italy","Vote":"Against"}]
        
    const result = Array.from(
      members
        .reduce((acc, o) => {
          if(!acc.has(o.Country)) acc.set(o.Country, {
            Country: o.Country,
            VoteFor: 0,
            VoteAgainst: 0
          })
          
          const item = acc.get(o.Country)
          
          if(o.Vote === 'For') item.VoteFor += 1
          else if(o.Vote === 'Against') item.VoteAgainst += 1
          
          return acc
        }, new Map())
        .values()
    )
    
    console.log(result)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-22
      • 2012-03-24
      • 1970-01-01
      • 2019-12-17
      • 1970-01-01
      • 2020-01-20
      • 2013-07-02
      • 1970-01-01
      相关资源
      最近更新 更多