I'm having trouble with the following code (will explain after) within a Vue SPA component:
const accountArray = Array.from(Object.values(this.accounts)[0]) // [0 is the sub-array I need, and won't change]
const urlId = this.$route.params.id // 3
const i = accountArray.findIndex(account => account.id === urlId) // -1
console.log(i) // -1, as it didnt found any matches
console.log(urlId) // 3
The this.accounts
is a computed property that returns an Observable object, and it works as expected (the 0 index is the sub-array of interest), hence my looping on it. The accountArray
variable also returns the array that I want to iterate over (it has an account with id = 3), but when it comes to the iteration predicate, it ALWAYS returns -1
when it should be returning 2
. Also, if I hard-code 3 instead of urlId
, it returns the 2
that I'm looking for. Why?
When I print the accountArray
, the output is the following:
I've made sure that this is not a Vuex reactivity problem, because I can refresh the page and it still returns me the arrays I need. What I'm missing here?
Thanks in advance!
You're using ===
comparison which expects the same value and same data type which is not true for your case. Your account.id
is number and your urlId
coming from route params is a string (3 !== "3"
).
Try converting route params id to a number before comparing it to account.id
.
const urlId = +this.$route.params.id // 3
Notice + sign in front of this.$route.params.id
used to convert a string to a number.
As an alternative, you could compare it using ==
which would return true for your 3 == "3"
case, but I suggest you to stick to the first advice.