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

如何将数组元素作为UniqueId键值对映射到对象数组

修改代码实现对应UniqueId赋值

原代码的问题是在map回调里固定了UniqueId的值,要实现两个数组元素的对应匹配,只需要利用map方法的第二个参数索引值来关联att数组的对应元素即可。

修改后的完整代码:

const characters = [
{
name: "Luke Skywalker",
height: "172",
mass: "77",
eye_color: "blue",
gender: "male",
},
{
name: "Darth Vader",
height: "202",
mass: "136",
eye_color: "yellow",
gender: "male",
},
{
name: "Leia Organa",
height: "150",
mass: "49",
eye_color: "brown",
gender: "female",
},
{
name: "Anakin Skywalker",
height: "188",
mass: "84",
eye_color: "blue",
gender: "male",
},
];

const att = ["B0117", "B5019", "B0821", "B0098"];
const attArr = characters.map((char, index) => {
  return { ...char, UniqueId: att[index] }
});
console.log(attArr);

关键修改点:

  • 给map的回调函数添加第二个参数index,该参数代表当前遍历的characters元素的索引位置
  • 将UniqueId的值从固定字符串改为att[index],让每个characters对象对应到att数组中同索引的唯一标识
  • 给变量att和attArr加上const声明,避免隐式全局变量,符合JavaScript编码最佳实践

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:20:28