Home > Back-end >  Array.from(Object).forEach not working with vue.js
Array.from(Object).forEach not working with vue.js

Time:03-31

I create object like this on my data() in vue.js 2 CLI:

data(){
    return{
        user: {
            user_mail: '',
            user_password: '',
            user_confirm_password : '',
            user_phone : '',
            user_fname: '',
            user_lname: '',
        },
    }
},

Now I'm trying to print this object on a the log useing mounted function:

mounted() {
    console.log(this.user)
}, 

It works fine. The problem starts when I trying to go through it with forEach:

mounted() {
    Array.from(this.user).forEach((value) => {
        console.log(value)
    });
},

In this situation I don't get any output on my log. Any suggestions? Thanks :)

CodePudding user response:

Array from creates an array from an iterable, which does not work on plain objects.

The Array.from() static method creates a new, shallow-copied Array instance from an array-like or iterable object.

You could use Object.values, Object.entries or Object.keys

Object.values(this.user).forEach((value) => {
  console.log(value)
});

CodePudding user response:

The Array.from() cannot create an array from your object. Instead of it, you could just use the old simple way:

for (const key in this.user) {
  console.log(this.user[key]);
}
  • Related