简体   繁体   English

使用另一个没有键的 id 数组从对象数组中查找值

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

I'm trying to find the names of clients from an array using the second array of client ids.我正在尝试使用第二个客户端 ID 数组从数组中查找客户端的名称。 I would try an old-school for loop but I think in vuejs this is not the optimal solution.我会尝试一个老式的 for 循环,但我认为在 vuejs 中这不是最佳解决方案。

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这是仅包含特定客户端 ID 的数组

selectedClientsIds = [1, 2, 4];

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.如果 selectedClientsIds 中的所有元素始终是客户端中的 id,您可以通过在客户端中查找它们来将名称映射到 selectedClientsIds 中的 id。 Like:喜欢:

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

Using only == because the ids in clients are strings.仅使用==因为客户端中的 id 是字符串。

I would try an old-school for loop but I think in vue.js this is not the optimal solution.我会尝试一个老式的 for 循环,但我认为在 vue.js 中这不是最佳解决方案。

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.这都是关于过滤数组的,这可以在 Vue 脚本中使用JavaScript完成,然后结果会将过滤后的数据绑定到模板中。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM