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:

Expected functionality:

Actual unwanted behavior:

    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:


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);