NodeJS 当对象的标记存在时,尝试增加计数器

cu6pst1q  于 2023-10-17  发布在  Node.js
关注(0)|答案(1)|浏览(193)

在下面的代码中,我想实现,每当标记值是新的,它应该被添加到一个数组。如果标签不存在,则将添加包含标签和计数器的对象。那也行
不起作用的是,当标签已经存在时,我想增加计数器。不管是什么原因,我得到了一个NaN作为结果。
recipes.js

  1. /* Count apperance of every tag */
  2. let tagCounter = [];
  3. allRecipes.forEach(recipe => {
  4. const tag = recipe.tag;
  5. // Suche nach dem Tag in tagCounter
  6. const existingTag = tagCounter.find(item => JSON.stringify(item.tag) === JSON.stringify(tag));
  7. if (existingTag) {
  8. // Das Tag wurde gefunden, erhöhe den Counter
  9. existingTag.tag.counter += 1;
  10. console.log(existingTag.tag.counter);
  11. } else {
  12. // Das Tag wurde nicht gefunden, füge es zu tagCounter hinzu
  13. tagCounter.push({ tag, counter: 1 });
  14. console.log("else");
  15. console.log(existingTag?.tag?.counter);
  16. }
  17. });
  18. console.log(tagCounter);
  19. res.status(200).json({resultArrayUniqueTags, tagCounter})

控制台:

  1. else
  2. undefined
  3. else
  4. undefined
  5. NaN
  6. NaN
  7. NaN
  8. NaN
  9. [ { tag: Breakfast, counter: 1 }, { tag: Lunch, counter: 1 } ]

我真的不明白为什么我不能增加计数器。当使用console.log(typeof)验证数据类型时,它显示“number”。

lsmd5eda

lsmd5eda1#

您应该执行existingTag.counter += 1;而不是existingTag.tag.counter += 1;
此外,console.log(existingTag.counter);代替console.log(existingTag.tag.counter);

相关问题