繁体   English   中英

从 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
     }
]

我有一个“工作”解决方案,我基本上是 go:

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

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

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

您可以通过它们的id和 map 收集的 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; }

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

 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属性键的 object,因此对 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM