Vue.js Can't iterate through object in method

11,272

Solution 1

You have to use var, let or const for a variable declaration (in strict mode):

for (const item in obj)
     ^^^^^

Solution 2

First you have to define item with the keyword const to make it a block-scope variable.

Next add this before the recursive call. Don't forget to define cardInfo within the data section.

You would also want to stick to Vue linting standards (I use ESLint when I created my project) so that you should use triple equal and delete semicolons etc.

Try this, it correctly logged the result into the console for me:

data () {
  return () {
    cardInfo: [
      // your data
    ]
  }
},
methods: {
  getJsonItem (lookup, obj = this.cardInfo) {
    for (const item in obj) {
      if (item === lookup) {
        console.log(obj[item])
      } else if (obj[item] instanceof Object) {
        this.getJsonItem(lookup, obj[item])
      }
    }
  }
},
mounted () {
  this.getJsonItem('brand')
}

If you call your method inside your template not your script you would not need to add this before it.

Share:
11,272
Kyle
Author by

Kyle

Updated on June 05, 2022

Comments

  • Kyle
    Kyle about 2 years

    I have a Vue.js component that has a data variable that's a JSON object and I've made a method that's meant to easily find items within this object by key, recursively.

    Here it is:

    getJsonItem(lookup, obj=this.cardInfo) {
      for (item in obj) {
        if (item == lookup) {
          return obj[item];
        } else if (obj[item] instanceof Object) {
          getJsonItem(lookup, obj[item]);
        }
      }
    },
    

    Now, this worked perfectly fine in the console outside of Vue JS, but when I try running it from within Vue JS as a method I get a "ReferenceError: item is not defined" error.

    Is there something funny going on with the scoping of variables in Vue JS that stops me from referencing the 'item' variable that's declared in the for loop?

    I'm sure it's probably something simple I'm not seeing.

  • Kyle
    Kyle over 6 years
    Can't +1 you for lack of rep, but thanks. I didn't even think of that, you helped a ton!
  • Alexander Gorg
    Alexander Gorg almost 4 years
    omg, Kyle! Just mark it with tick as the correct answer!