Home > OS >  Find values from array of objects using another array of ids without keys
Find values from array of objects using another array of ids without keys

Time:05-30

I'm trying to find the names of clients from an array using the second array of client ids. I would try an old-school for loop but I think in vuejs this is not the optimal solution.

This is my main array

clients = [
  {id: "1", name: "Bob"},
  {id: "2", name: "Mary"},
  {id: "3", name: "John"},
  {id: "4", name: "Petter"}
];

This is the array that contains only specific client ids

selectedClientsIds = [1, 2, 4];

CodePudding user response:

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.

CodePudding user response:

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>

  • Related