Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I loop object observer on vue.js 2?

If I console.log(this.list), the result like this :

enter image description here

this.list.forEach(function (user) {
    selected.push(user.id);
});

There exist error :

Uncaught TypeError: this.list.forEach is not a function

How can I solve this error?

like image 221
Success Man Avatar asked Nov 20 '17 08:11

Success Man


Video Answer


1 Answers

Is this.list not an Array?

If this.list is array-like (there must be a length property on that object), you should be able to do:

Array.prototype.forEach.call(this.list, user => {
  // ...
})

or

Array.from(this.list).forEach(user => {
  // ...
})

or

[...this.list].forEach(user => {
  // ...
})

Otherwise if this.list is just a plain object, you can do:

Object.keys(this.list).forEach(key => {
  const user = this.list[key]
  // ...
})

or

Object.entries(this.list).forEach(([key, user]) => {
  // ...
})
like image 184
Decade Moon Avatar answered Nov 03 '22 09:11

Decade Moon