You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将ID数组元素替换为匹配的对象名称?兼顾性能的最优方案

问题:高效将ID嵌套数组转换为名称嵌套数组

假设有一个ID嵌套数组:

const ids = [[1, 2, 3], [2, 3], [3]]

同时有一个包含各ID对应名称的对象数组:

const obj = [
    { id: 1, name: "One" },
    { id: 2, name: "Two" },
    { id: 3, name: "Three" },
];

如何以最优方式得到目标数组 [["One", "Two", "Three"], ["Two", "Three"], ["Three"]]?担忧嵌套映射会带来性能问题。


最优解决方案

核心思路是先构建ID到名称的映射表,把O(n)的查找变成O(1),彻底避免嵌套遍历带来的高时间复杂度问题。

1. 构建ID-名称映射表

先遍历一次obj数组,生成一个以ID为键、名称为值的对象,后续查找名称时直接通过键获取,无需反复遍历obj:

const idToName = obj.reduce((map, item) => {
  map[item.id] = item.name;
  return map;
}, {});

生成的idToName结构为:{1: "One", 2: "Two", 3: "Three"}

2. 转换ID数组为名称数组

再遍历ids嵌套数组,对每个子数组中的ID,直接从映射表中取出对应名称:

const result = ids.map(subIds => subIds.map(id => idToName[id]));

性能对比

  • 直接嵌套使用obj.find的方式,时间复杂度是O(m*n)(m是ids的子数组数量,n是obj的长度),数据量大时性能会急剧下降;
  • 先构建映射表的方式时间复杂度是O(n + m*k)(k是每个子数组的平均长度),属于线性复杂度,数据规模越大,性能优势越明显。

完整代码示例

const ids = [[1, 2, 3], [2, 3], [3]];
const obj = [
    { id: 1, name: "One" },
    { id: 2, name: "Two" },
    { id: 3, name: "Three" },
];

// 构建映射表
const idToName = obj.reduce((map, item) => {
  map[item.id] = item.name;
  return map;
}, {});

// 转换数组
const result = ids.map(subIds => subIds.map(id => idToName[id]));

console.log(result);
// 输出:[["One", "Two", "Three"], ["Two", "Three"], ["Three"]]

内容的提问来源于stack exchange,提问作者kkkkkkkkkkkkkkkkk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:04:05