0

I'm trying to find clients' names 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];
1
  • 1
    Please try: console.log(clients.filter(({ id }) => selectedClientsIds.includes(+id))?.map(({ name }) => name)); and check if displays an array of names matching the ids in the selectedClientsIds array. Commented May 30, 2022 at 2:00

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.