[英]How to get a list of objects by their id using an array of numbers
NOTE: I understand that the title is phrased ambiguously and the explanation below is simplistic, apologies I'm a little new to JS注意:我知道标题的措辞含糊不清,下面的解释很简单,抱歉我对 JS 有点陌生
I have this array of objects (this.listOfAnimals).我有这个对象数组(this.listOfAnimals)。 I believe the purple represents the ids of each object.
我相信紫色代表每个对象的 ID。
I have a list of numbers below which are dynamically generated:我有一个动态生成的数字列表:
this.arrayOfNumbers = [0,1,2,3,4,5] which is set using:
while(this.firstNumber <= this.lastNumber) {
this.arrayOfNumbers.push(this.firstNumber++);
}
I need to get a list of items from this.listOfAnimals with ids = the numbers in the array this.arrayOfNumbers.我需要从 this.listOfAnimals 中获取一个项目列表,其中 ids = 数组 this.arrayOfNumbers 中的数字。 How can I do this?
我怎样才能做到这一点?
For example, I need a list of all items in this.listOfAnimals whose ids are 0,1,2,3,4,5 (coming from the array in the 2nd image).例如,我需要 this.listOfAnimals 中所有项目的列表,其 ids 为 0,1,2,3,4,5(来自第二张图像中的数组)。 All of the data is dynamically generated so I can't use hardcoded code like this.listOfAnimals[0].
所有数据都是动态生成的,所以我不能使用像 this.listOfAnimals[0] 这样的硬编码代码。
尝试这个
this.arrayOfNumbers.map(id => { console.log(this.listOfAnimals[id]); });
使用map()
迭代arrayOfNumbers
,并将这些值用作listOfAnimals
索引
let selectedAnimals = this.arrayOfNumbers.map(n => this.listOfAnimals[n]);
If you have lodash in your project, _.at can do the trick:如果您的项目中有 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.