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

JavaScript如何将字符串数组元素按序作为属性添加到对象数组中

JavaScript按顺序给对象数组添加对应link属性实现方案

核心逻辑:两个数组的元素顺序是一一匹配的,遍历对象数组时,通过当前遍历下标从链接数组中取对应值,赋值给对象的link属性即可。

方法1:map生成新数组(推荐,不污染原数据)

这个方法不会修改原始的对象数组和内部对象,会返回全新的结果数组,适合不想改动原数据的场景:

const links = ['/nft-card', '/landing'];
const originList = [
  { id: 1, name: 'NFT Preview Card' },
  { id: 2, name: 'Remote Landing Page' }
];

const result = originList.map((item, index) => ({
  ...item,
  link: links[index]
}));

方法2:直接修改原数组

如果不需要保留原始数组的结构,可以直接遍历原数组追加属性,性能更好:

originList.forEach((item, index) => {
  item.link = links[index];
});
// 执行完后originList就是目标结果

注意:使用前要确认两个数组长度一致、元素顺序对应,否则会出现link匹配错位、值为undefined的问题。

执行后打印结果就能得到预期格式:

console.log(result);
/*
[
  { id: 1, name: 'NFT Preview Card', link: "/nft-card" },
  { id: 2, name: 'Remote Landing Page', link: "/landing" }
]
*/

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 07:01:03