Search code examples
javascripthtmlnode.jsarraysobject

Attempting to increase the counter, when the object's tag exist


In the following code I want to achieve, that whenever the tag value is new, it should be added to an Array. If the tag does not exist, the object comprising the tag and the counter will be added. That works.

What does not work is, that I want to increase the counter, when the tag exists already. For whatever reason, I get a NaN as a result.

recipes.js

    /* Count apperance of every tag */
    let tagCounter = [];
    allRecipes.forEach(recipe => {
        const tag = recipe.tag;

        // Suche nach dem Tag in tagCounter
        const existingTag = tagCounter.find(item => JSON.stringify(item.tag) === JSON.stringify(tag));
        if (existingTag) {
        // Das Tag wurde gefunden, erhöhe den Counter
        existingTag.tag.counter += 1;
        console.log(existingTag.tag.counter);

        } else {
        // Das Tag wurde nicht gefunden, füge es zu tagCounter hinzu
        tagCounter.push({ tag, counter: 1 });
        console.log("else");
        console.log(existingTag?.tag?.counter);

        }
    });
    
    console.log(tagCounter);
  
    res.status(200).json({resultArrayUniqueTags, tagCounter})

console:

else
undefined
else
undefined
NaN
NaN
NaN
NaN
[ { tag: Breakfast, counter: 1 }, { tag: Lunch, counter: 1 } ]

I really don't get why I cannot increase the counter. When verifying the data type with console.log(typeof) it shows me "number".


Solution

  • You should be doing existingTag.counter += 1; instead of existingTag.tag.counter += 1;

    Also, console.log(existingTag.counter); instead of console.log(existingTag.tag.counter);