Home > OS >  Vue - Using a list of object from data in a function on methods, to check if is equal with an input
Vue - Using a list of object from data in a function on methods, to check if is equal with an input

Time:07-06

So I am new in Vue and JS in general, and I am trying to do a user and password check with framework vue. In the .js I have a list object inside in data, what contain parameters like user and password. Then I use this list in a function on methods, to check if the input is equal to one of the user in the list with a if.

the problem is, all the items on methods are undefined using the respective console log (but those items exist with the proper v-for in the html).

this is a example of the code.

const app=new Vue({
el:"#app",
data:{
    list:[
        {user:'cpalma',password:'123456'},
        {user:'cjara',password:'654321'}
    ],
    tryUser:'',
    tryPass:'', 
},
methods:{
    checkPass(){
        console.log(this.list.user);
        for(item in this.list){
            if(item.user == this.tryUser){
              // rest of code
        }
    }
}

Vue version is 2.5 "checkPass" is execute with a button. tryUser and tryPass are get from the html with his respective v-model.

So if anyone can explain what is my error and how to fix it I will be in eternally grateful.

CodePudding user response:

Observations :

  • As list is an array of objects. You can't access the objects properties directly via dot(.) notation. You have to access those via index.

    this.list.forEach(obj => {
      console.log(obj.user)
    });
    
  • To iterate arrays, Use for...of loop instead of for...in which is basically more useful for objects not arrays.

const list = [
  {user:'cpalma',password:'123456'},
  {user:'cjara',password:'654321'}
];

for (const userDetail of list) { // ✅
    console.log(userDetail.user);
}

for (const userDetail in list) { // ❌
    console.log(userDetail);
}

CodePudding user response:

for with in returns and index of the item due to this you are getting undefined

try the correct snippet as below:

let list =[
        {user:'cpalma',password:'123456'},
        {user:'cjara',password:'654321'}
    ]

for(item in list){console.log(list[item].user)}

To simplify it you can also use forEach:

let list =[
        {user:'cpalma',password:'123456'},
        {user:'cjara',password:'654321'}
    ]

list.forEach(item=>{
console.log(item.user)
//Rest of the logic
})

  • Related