[Vuejs]-Find values from array of objects using another array of ids without keys

2👍

If all elements in selectedClientsIds are always ids in clients, you could map the name to the ids in selectedClientsIds by finding them in clients. Like:

const names = selectedClientsIds.map((id) => clients.find((el) => el.id == id).name);

Using only == because the ids in clients are strings.

👤seb

1👍

I would try an old-school for loop but I think in vue.js this is not the optimal solution.

It’s all about filtering the array, which can be done using JavaScript inside Vue script and then result will get bind the filtered data into the template.

Demo :

new Vue({
  el: '#app',
  data: {
    clients: [
      {id: "1", name: "Bob"},
      {id: "2", name: "Mary"},
      {id: "3", name: "John"},
      {id: "4", name: "Petter"}
    ],
    selectedClientsIds: [1, 2, 4]
  },
mounted() {
    this.clients = this.clients.filter(({ id }) => this.selectedClientsIds.includes(parseInt(id)));
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <ul>
    <li v-for="client in clients" :key="client.id">{{ client.name }}</li>
  </ul>
</div>

Leave a comment