javascript - 显示每个标签出现的次数
问题描述
我有一个用户对象,我试图显示每个标签出现的次数。我在 ExaltedToast 代码中编辑
我期望的输出是:
测验:1
厌烦:1
结果:1
: 1
场合:2
..等等
我得到的输出是:
{"quis":1,"irure":1,"consequat":1,"ut":1,"occaecat":2,"esse":1,"qui":1,"in":1," duis":1,"officia":1,"ipsum":1,"incidudunt":2,"ex":1}
我的数组对象
const users = [
{
age: 21,
eyeColor: "green",
name: "Gregory Villarreal",
company: "BLUPLANET",
tags: ["quis", "irure", "consequat", "ut", "occaecat"],
},
{
age: 39,
eyeColor: "brown",
name: "Bowman Jensen",
company: "HOMETOWN",
tags: ["esse", "qui", "in", "duis", "occaecat"],
},
{
age: 35,
eyeColor: "brown",
name: "Berg Carson",
company: "WRAPTURE",
tags: ["officia", "ipsum", "incididunt", "incididunt", "ex"],
},
];
到目前为止我的代码
// OLD CODE
// get the tags from the array
const userTags = users.map((user) => (user.tags));
// count the tag occurrences
const tagCount = userTags.reduce((obj, e) => {
obj[e] = (obj[e] || 0) + 1;
return obj;
}, {});
// display the tag occurrences
let div = document.createElement('div');
div.innerHTML = JSON.stringify(tagCount);
document.body.appendChild(div);
// CURRENT CODE
users.forEach((user) => {
user.tags.forEach((tag) => {
tagCount[tag] = (tagCount[tag] | 0) + 1;
});
});
let div = document.createElement('div');
div.innerHTML = JSON.stringify(tagCount);
document.body.appendChild(div);
我有一个 JSBIN https://jsbin.com/leqeludahi/和一个代码片段
const users = [
{
age: 21,
eyeColor: "green",
name: "Gregory Villarreal",
company: "BLUPLANET",
tags: ["quis", "irure", "consequat", "ut", "occaecat"],
},
{
age: 39,
eyeColor: "brown",
name: "Bowman Jensen",
company: "HOMETOWN",
tags: ["esse", "qui", "in", "duis", "occaecat"],
},
{
age: 35,
eyeColor: "brown",
name: "Berg Carson",
company: "WRAPTURE",
tags: ["officia", "ipsum", "incididunt", "incididunt", "ex"],
},
];
const tagCount = {};
users.forEach((user) => {
user.tags.forEach((tag) => {
tagCount[tag] = (tagCount[tag] | 0) + 1;
});
});
let div = document.createElement('div');
div.innerHTML = JSON.stringify(tagCount);
// div.innerHTML = tagCount.join('\n');
document.body.appendChild(div);
解决方案
您已经接近了,您只需要额外遍历数组中的标签,而不仅仅是将数组直接添加到对象中。
// Get the tags from the array
const userTags = users.map((user) => user.tags);
// Count the tag occurrences
const tagCount = userTags.reduce((obj, e) => {
for (let tag of e) {
obj[tag] = (obj[tag] || 0) + 1;
}
return obj;
}, {});
一个相当干净的解决方案是在forEach
.
let tagCount = {};
users.forEach((user) => {
user.tags.forEach((tag) => {
tagCount[tag] = (tagCount[tag] | 0) + 1;
});
});
推荐阅读
- ios - 在IOS中将UISearchbar背景颜色设置为白色
- c++ - 找到一对圆锥曲线的内公切线
- visual-studio-code - 直接使用 Linux 在 samba 中编辑文件?
- python - 为什么输入字段中的 request.form 不起作用?
- python-3.x - 与括号一起使用时 Python lambda 函数错误
- mysql - 如何使用 apache 写入(/var/lib/mysql-files)?
- javascript - 我的 Discord.js Bot 欢迎消息突然停止工作
- google-cloud-endpoints - 您如何自定义 Google Cloud Endpoints 完成的 java JSON 序列化?
- javascript - 如何重复特定次数的功能直到停止
- c# - 将 XML 消息发送到 MSMQ,无需任何格式