【问题标题】:Get total values获取总值
【发布时间】:2018-10-21 03:58:06
【问题描述】:

谢谢你。

【问题讨论】:

  • 这是我的数据。这不是问题。一切正常。
  • 我已经提到了数据的样子。 Pitcher Pitcher Catcher Batter Batter 知道还有什么出席是无关紧要的。
  • @JaromandaX 我把最后一部分改成:=> <li key={key}>{key} - {value}</li>)
  • @JaromandaX 仍然得到那个该死的 4 ......
  • @JaromandaX 它正在添加所有项目。这就是为什么它是 4。只有三个独特的项目。总共四项。

标签: javascript reactjs react-native react-redux


【解决方案1】:

假设标签最终是["Pitcher","Pitcher","Catcher","Batter"];

const tags = ["Pitcher","Pitcher","Catcher","Batter"];
const result = Object.entries(tags.reduce((r,t)=>(r[t]=(r[t]||0)+1,r),{})).map(([k,v])=>`<li key="${k}">${k} - ${v}</li>`).join('\n');
console.log(result);

当然,由于你使用它的方式看不到标签的确切内容,很可能是标签更像

const tags = ["","Pitcher","","Pitcher","","Catcher","","Batter"];
const result = Object.entries(tags.reduce((r,t)=>(r[t]=(r[t]||0)+1,r),{})).map(([k,v])=>`<li key="${k}">${k} - ${v}</li>`).join('\n');
console.log(tags.join('')); // you can't see the empty tags here
console.log(result); // but this is the result

这就是为什么我要求你发布 attendance 是什么,看看数据发生了什么

但是,按照我的建议使用过滤器...

const tags = ["","Pitcher","","Pitcher","","Catcher","","Batter"];
const result = Object.entries(tags.filter(t=>t).reduce((r,t)=>(r[t]=(r[t]||0)+1,r),{})).map(([k,v])=>`<li key="${k}">${k} - ${v}</li>`).join('\n');
console.log(tags.join('')); // you can't see the empty tags here
console.log(result); // with filter, everything is good again

【讨论】:

  • 那么,如果这是一个问题,您将如何忽略空值?
【解决方案2】:

如果tags 是一个字符串数组(标签名称),那么您可以使用reduce 导出期望的输出。

例子

var tags = ['Pitcher', 'Pitcher', 'Catcher', 'Batter', 'Batter'];
var result = tags.reduce((acc, val) => {
  acc[val] = acc[val] || 0;
  acc[val] = acc[val] + 1;
  return acc;
}, {});
console.log(result);

希望这会有所帮助!

编辑 要将最终对象转换为字符串数组,可以使用.map

Object.entries(result).map(([k, v]) => `${k}-${v}`);

感谢Jaromanda X的提醒

【讨论】:

  • 最终输出中缺少什么?
  • 我这样做是为了反应。这是我到处都能看到的答案,但对 React 没有帮助。 Objects are not valid as a React child (found: object with keys {, Pitcher, Catcher, Batter})
  • 你是如何使用最终对象的?
  • {result}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
  • 2020-07-20
  • 2019-11-05
  • 2020-11-21
相关资源
最近更新 更多