【问题标题】:How to get a list of objects by their id using an array of numbers如何使用数字数组通过其 id 获取对象列表
【发布时间】:2021-02-03 16:55:06
【问题描述】:

注意:我理解标题措辞含糊,以下解释过于简单,抱歉我对 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 中 ID 为 0,1,2,3,4,5 的所有项目的列表(来自第二张图像中的数组)。所有数据都是动态生成的,所以我不能使用像 this.listOfAnimals[0] 这样的硬编码代码。

【问题讨论】:

标签: javascript arrays json loops dynamic


【解决方案1】:

使用map() 迭代arrayOfNumbers,并将值用作listOfAnimals 的索引

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

【讨论】:

    【解决方案2】:

    试试这个

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

    【讨论】:

      【解决方案3】:

      如果您的项目中有 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"]
      &lt;script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"&gt;&lt;/script&gt;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-18
        相关资源
        最近更新 更多