从 ID 列表中获取对象列表 javascript

Get list of objects from a list of ids javascript

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

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);
}

但最终我想知道这是否是最有效的方法,因为在我的真实示例中,我的水果清单可能有数千个水果,而且我同样可以有一个巨大的清单ids.

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

您可以通过“散列”id 然后仅通过查找过滤它们来以更高效的方式做到这一点,如下所示:

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);

我假设对象中的 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);

您可以通过 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; }