let $object= [
{
tagName: "01",
contentID: [100, 200],
occurrences: 2
},
{
tagName: "02",
contentID: [200, 300],
occurrences: 2
},
{
tagName: "03",
contentID: [100, 200, 300],
occurrences: 3
},
{
tagName: "04",
contentID: [300],
occurrences: 1
}];
我想在 tagName
匹配时增加 occurrences
的值。我应该如何增加出现
值/计数?
//let tagManagerArr = [];
//全局范围
for (let content of contents) {
contentId = content.contentID;
entityType = content.entityType;
let tags = content.tags,
check = false;//check gives me whether a tagName is already present in the '$object' array..
for (let tagName of tags) {
console.log("---------------------------------------")
tagManagerArr.forEach(
(arrayItem) => {
if (arrayItem.tagName === tag) {
check = true;
}
}
);
//tagManagerArr.find(
// (element) => {
// if (element.tagName === tagName) {
// check = true;
// }
// });
if (!check) {
tagObject = {};
tagObject['tagName'] = tagName;
tagObject['contentID'] = [];
tagObject['occurrences'] = 1;
tagObject['contentID'].push(contentId);
} else {
tagManagerArr.find(
(element) => {
if (element.tagName === tagName) {
if (!element.contentID.includes(contentId)) {
element.contentID.push(contentId);
}
element.occurrences += 1;
}
});
}
tagManagerArr.push(tagObject);
}
}
这工作正常,但出现错误。有任何线索吗?
最佳答案
使用从标签名称到属性的映射会更容易、更高效:
// pick a better name
const map = new Map();
for (const content of contents) {
for (const tagName of content.tags) {
let tagObject = map.get(tagName);
if (tagObject === undefined) {
map.set(tagName, tagObject = {
contentID: new Set(),
occurrences: 0,
});
}
tagObject.occurrences++;
tagObject.contentID.add(content.contentID);
}
}
然后可以将其转换为数组格式:
const tagManagerArr = Array.from(map,
([tagName, {contentID, occurrences}]) => ({
tagName,
contentID: Array.from(contentID),
occurrences,
}));
关于javascript - 增加JS数组中的Object键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52764040/