Search code examples
javascriptvue.js

Why does this for loop never return true?


I have a VueJS computed function that I want to use to control whether or not something shows up on a page. I'm having trouble with it, I expect it to end iterating on return but it continues going and never sustains return true

HTML element on vue page:

<div v-if="infoExists">Some Stuff Here</div>

I have a function infoExists that:

  • loops through all of a certain set of objects within a parent object
  • checks if some information within the object exists (eventually it should test if it === a certain value, but I have issues even with it just existing, so I'm trying to solve that first)

Expected functionality:

  • returns true if any one item in object has item.info
  • stops iterating the for loop if a single item with item.info is found, and simply returns true for the duration of the page load

Actual unwanted behavior:

  • Iterates through all items in the set correctly
  • Finds when an item has item.info correctly
  • Continues to iterate throughout the rest of the items
  • Never returns as true even if every item in object has item.info
  • If I set return false at the end outside of the loop, it always returns as false
    infoExists() {
      console.log('infoExists') // always prints correctly

      Object.values(this.set.items).forEach( (item) => {
        console.log(item) // logs correct item, keeps printing items even after an item containing item.info is passed previously
        if (item.info) {
          console.log('has info') // correctly logs when has info
          return true; // expect for the loop to break here and for the function to return true
        }
      } );

       // return false; // if this is uncommented, it always returns false
    },

How do I get this to simply:

  • Check if any item has item.info
  • If it does, return true
  • If no item has item.info return false

Solution

  • The appropriate method here is Array#some.

    The some() method of Array instances tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.

    return Object.values(this.set.items).some(item => item.info);