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

如何根据字符串数组匹配对象数组ID,获取对应标签或原ID

从对象数组匹配ID获取标签,不存在则保留原ID的实现方案

需求说明

遍历字符串数组中的每个ID:

  • 若ID在对象数组中存在,取对应对象的label值
  • 若ID不存在,保留原ID值
    最终将所有结果存入新数组。

示例数据

var objectVar = [{ id: '1', label: 'One' }, { id: '2', label: 'Two' }, { id: '3', label: 'Three' }];
var arrVar = ['1', '2', '3', '4'];

预期结果

result = ['One', 'Two', 'Three', '4'];

实现方案

方案一:直接遍历查找(适合小规模数据)

利用Array.map()遍历目标数组,结合Array.find()查找匹配的对象:

const result = arrVar.map(id => {
  const match = objectVar.find(item => item.id === id);
  return match ? match.label : id;
});

方案二:构建映射表(适合大规模数据)

先将对象数组转换成ID到label的映射表,避免重复查找,提升性能:

// 构建ID与label的映射Map
const idToLabel = new Map(objectVar.map(item => [item.id, item.label]));
// 生成结果数组
const result = arrVar.map(id => idToLabel.get(id) || id);

这种方式的时间复杂度为O(n+m)(n为对象数组长度,m为目标数组长度),比方案一的O(n*m)更高效,数据量越大优势越明显。

内容的提问来源于stack exchange,提问作者fullstack-developer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 00:36:27