【发布时间】:2021-09-23 22:52:52
【问题描述】:
我有一个用户对象,我试图显示每个标签出现的次数。 我在 ExaltedToast 代码中编辑过
我期望的输出是:
quis: 1
irure: 1
结果:1
ut: 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);
【问题讨论】:
标签: javascript arrays object counting