Auzy
Auzy

Reputation: 2155

Vue JS run computed property for each key value of another computed property

I have a computed property:

relateditems () {
 return this.related.find((relation) => {
  return relation.id === this.currentItem.id
 })
},

with the following output:

relateditems:Object
   -KQ1hiTWoqAU77hiKcBZ:true
   -KQ1tTqLrtUvGnBTsL-M:true
   id:"-KQ1if2Zv3R9FdkJz_1_"

I'm trying to create another computed property that then loops through the relateditems object and finds a relation with the matching ID for the first two keys.

The following doesn't work but I think it gives the idea:

relateditemsdata () {
 let test = []
 for (var key in this.relateditems) {
  this.items.find((relateditem) => {
   relateditem.id === key.id
    test.push(relateditem)
   })
  }
  return test
}

Upvotes: 2

Views: 2769

Answers (2)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

I think calling a computed property in another one is not a good way, so you could add a watcher property in order to watch the first computed property and update a data object property based on that one like :

data() {
  return {
    relateditemsdata: [],
  }
},

computed: {
  relateditems() {
    return this.related.find(relation => {
      return relation.id === this.currentItem.id
    })
  },
},

watch: {
  relateditems(val) {
    for (var key in this.relateditems) {
      this.items.find(relateditem => {
        relateditem.id === key.id
        relateditemsdata.push(relateditem)
      })
    }
  },
},

Upvotes: 1

MarcRo
MarcRo

Reputation: 2473

Seems like your problem is not related to Vue.

Your key.id is undefined in the for..in loop. You would have to use this.relateditems[key] to access the value or just key to access the key. Since you do not want filter your other array for the 'id' key, you should also filter your object-keys first.

E.g.

relatedItems() {
  return this.related.find((item) => {
    return this.item.id == this.currentItem.id;
  });
} // returns first objects with the same id

relatedItemsData() {
  // grabs all keys except 'id'
  const keys = Object.keys(this.relateditems).filter((key) => key != 'id');
  this.items.filter((item) => {
    return keys.indexOf(item.id) != -1; // checks if item.id is inside the keys-array
  });
} // returns again array of objects;

Instead of a nested loop, you can also just use the Array.prototype.filter() function, like above.

Upvotes: 0

Related Questions