NOTE: I understand that the title is phrased ambiguously and the explanation below is simplistic, apologies I'm a little new to JS
I have this array of objects (this.listOfAnimals). I believe the purple represents the ids of each object.
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. 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). All of the data is dynamically generated so I can't use hardcoded code like 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:
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.