margherita pizza
margherita pizza

Reputation: 7185

Vuejs how to use computed properties with a forEach loop

My use case is something like this,

  1. I loop through an array of objects to populate a drop-down menu.
  2. If I v-model that drop down I can only get the object id or name. But I can get id and name both at the same time.
  3. So I need computed property to find the id of the selected object.

This is my v-select

<v-select
    label="Select an item"
    :items="items"
    item-text="name"
    v-model="item_name">
/>

This is my computed property

computed: {
  id() {
    this.items.forEach(element => {
      if (element.name == this.item_name) {
        return (this.item = element.id);
      }
    });
  }  
}

What went wrong with my computed property I expected to {{item}} to print the id of the selected item but it didn't.

Upvotes: 5

Views: 8228

Answers (2)

TymoteuszLao
TymoteuszLao

Reputation: 954

The v-select component has return-object prop. Maybe try to use this to retrieve name and id at the same time, so the computed property will not be necessary at all.

Example:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: {
    items: [{
        id: 1,
        name: 'test1'
      },
      {
        id: 2,
        name: 'test2'
      },
      {
        id: 3,
        name: 'test3'
      },
    ],
    item: null,
  },
  methods: {
    onSelect() {
      console.log(this.item);
    },
  },
});
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet">

<div id="app">
  <v-app>
    <v-main>

      <v-select v-model="item" :items="items" item-text="name" return-object @change="onSelect"/>
    </v-main>
  </v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>

Upvotes: 0

aprouja1
aprouja1

Reputation: 1810

You may wan to use find() instead

computed: {
        id() {
          return this.items.find(element => {
            return element.name == this.item.name
          }).id;
        }

  }

This will first find the element in the Array that matches the condition in the function, and then the id of that element

Upvotes: 2

Related Questions