![](/img/trans.png)
[英]How to construct an array of objects by using the keys of another array of objects and values from the array of arrays?
[英]Find values from array of objects using another array of ids without keys
我正在嘗試使用第二個客戶端 ID 數組從數組中查找客戶端的名稱。 我會嘗試一個老式的 for 循環,但我認為在 vuejs 中這不是最佳解決方案。
這是我的主要數組
clients = [
{id: "1", name: "Bob"},
{id: "2", name: "Mary"},
{id: "3", name: "John"},
{id: "4", name: "Petter"}
];
這是僅包含特定客戶端 ID 的數組
selectedClientsIds = [1, 2, 4];
如果 selectedClientsIds 中的所有元素始終是客戶端中的 id,您可以通過在客戶端中查找它們來將名稱映射到 selectedClientsIds 中的 id。 喜歡:
const names = selectedClientsIds.map((id) => clients.find((el) => el.id == id).name);
僅使用==
因為客戶端中的 id 是字符串。
我會嘗試一個老式的 for 循環,但我認為在 vue.js 中這不是最佳解決方案。
這都是關於過濾數組的,這可以在 Vue 腳本中使用JavaScript
完成,然后結果會將過濾后的數據綁定到模板中。
演示:
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.