簡體   English   中英

如何使用數字數組按 id 獲取對象列表

[英]How to get a list of objects by their id using an array of numbers

注意:我知道標題的措辭含糊不清,下面的解釋很簡單,抱歉我對 JS 有點陌生

我有這個對象數組(this.listOfAnimals)。 我相信紫色代表每個對象的 ID。

在此處輸入圖片說明

我有一個動態生成的數字列表:

this.arrayOfNumbers = [0,1,2,3,4,5] which is set using:

while(this.firstNumber <= this.lastNumber) {
  this.arrayOfNumbers.push(this.firstNumber++);
}

在此處輸入圖片說明

我需要從 this.listOfAnimals 中獲取一個項目列表,其中 ids = 數組 this.arrayOfNumbers 中的數字。 我怎樣才能做到這一點?

例如,我需要 this.listOfAnimals 中所有項目的列表,其 ids 為 0,1,2,3,4,5(來自第二張圖像中的數組)。 所有數據都是動態生成的,所以我不能使用像 this.listOfAnimals[0] 這樣的硬編碼代碼。

嘗試這個

this.arrayOfNumbers.map(id => { console.log(this.listOfAnimals[id]); });

使用map()迭代arrayOfNumbers ,並將這些值用作listOfAnimals索引

let selectedAnimals = this.arrayOfNumbers.map(n => this.listOfAnimals[n]);

如果您的項目中有 lodash, _.at可以解決問題:

 const letters = ['a', 'b', 'c', 'd', 'e', 'f']; const indices = [0, 2, 4]; const selected = _.at(letters, indices) console.log(selected); // ["a", "c", "e"]
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM