moses toh
moses toh

Reputation: 13172

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?

Upvotes: 13

Views: 19806

Answers (2)

Abdullah Aman
Abdullah Aman

Reputation: 1620

Here is a way to loop over an observer array in Vue:

let keys = Object.keys(myObserverArray);

keys.forEach(key => {
   let item = myObserverArray[key];
   //...work with item
})

Upvotes: 3

Decade Moon
Decade Moon

Reputation: 34286

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]) => {
  // ...
})

Upvotes: 22

Related Questions