Vue.js Can't iterate through object in method
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.
![Kyle](https://lh4.googleusercontent.com/-WOLkl8LnGA4/AAAAAAAAAAI/AAAAAAAAAEg/ZIrwvGdP9Gc/photo.jpg?sz=256)
Kyle
Updated on June 05, 2022Comments
-
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.
-
D. Pareek over 6 yearsI think you are confusing with v-for directive, Please check here : vuejs.org/v2/guide/list.html
-
-
Kyle over 6 yearsCan't +1 you for lack of rep, but thanks. I didn't even think of that, you helped a ton!
-
Alexander Gorg almost 4 yearsomg, Kyle! Just mark it with tick as the correct answer!