【问题标题】:Get list of objects from a list of ids javascript从 ids javascript 列表中获取对象列表
【发布时间】:2021-06-16 07:12:59
【问题描述】:

我有一个对象列表,它们看起来像这样:

const fruit = [
     {
          name: 'banana',
          id: 1
     },
     {
          name: 'apple',
          id: 8
     },
     {
          name: 'orange',
          id: 3
     }
];

我有一个 ID 列表:

const ids = [8, 1];

我希望在我的 id 列表中获取所有具有 id 的“水果”,即我希望我的结果看起来像:

const result = [
     {
          name: 'apple',
          id: 8
     },
     {
          name: 'banana',
          id: 1
     }
]

我基本上有一个“有效”的解决方案:

let result = [];
for (let i = 0; i < ids.length; i += 1) {
     const foundFruit = fruit.find(x => x.id === ids[i]);
     result.push(foundFruit);
}

但最终我想知道这是否是最有效的方法,就像在我的真实示例中一样,我的水果列表可能有数千个水果长,而且我同样可以有一个巨大的 id 列表。

这种方法是最好的还是有更有效的方法来映射这些结果?

【问题讨论】:

  • 当然,只要fruitMap = new Map(fruit.map(f =&gt; [f.id, f])) 然后result = ids.map(id =&gt; fruitMap.get(id))

标签: javascript arrays object search find


【解决方案1】:

您可以通过“散列”ids 以更高效的方式完成此操作,然后仅通过查找过滤它们,如下所示:

const fruit = [
     {
          name: 'banana',
          id: 1
     },
     {
          name: 'apple',
          id: 8
     },
     {
          name: 'orange',
          id: 3
     }
];

const ids = [8, 1];

const result = fruit.filter(function (value) {
// return this.delete(value.id); // or use this return for unique ids
  return this.has(value.id);
}, new Set(ids));

console.log(result);

【讨论】:

    【解决方案2】:

    我假设对象中的id 属性是唯一的,如果是这种情况,那么下面的解决方案会更好。

    我将对象数组转换为具有 id 属性键的对象,因此查找 id 变得高效。

    const fruit = [
         {
              name: 'banana',
              id: 1
         },
         {
              name: 'apple',
              id: 8
         },
         {
              name: 'orange',
              id: 3
         }
    ];
    
    var fruitsObj = {};
    
    fruit.forEach(function (o) {
      fruitsObj[o.id] = o.name;
    });
    
    const ids = [8, 1];
    
    var result = [];
    
    ids.forEach(function (x){
      if (fruitsObj[x]) {
        result.push({name: fruitsObj[x], id: x});
      }
    });
    
    console.log(result);

    【讨论】:

      【解决方案3】:

      您可以通过id 收集所有水果并映射收集到的 id。

      const
          fruits = [{ name: 'banana', id: 1 }, { name: 'apple', id: 8 }, { name: 'orange', id: 3 }],
          ids = [8, 1],
          fruitsById = {};
      
      for (const fruit of fruits) fruitsById[fruit.id] = fruit;
      
      const result = ids.map(id => fruitsById[id]);
      
      console.log(result);
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-08
        • 2014-09-28
        • 2019-05-08
        相关资源
        最近更新 更多