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

如何将普通数组元素按索引添加到对象数组的每个对象中?

问题描述

我有一个普通数值数组array1和一个对象数组arrayofObj,想把array1中对应索引的元素添加到arrayofObj的每个对象里,新增一个val属性。目前只能给指定索引的对象添加对应元素,希望实现每个对象都新增val属性,值为array1中同索引的元素。

现有代码:

const array1 = [1, 2, 43, 5];

const arrayofObj = [
  {
    key: 1,
    value: 3,
  },
  {
    key: 2,
    value: 10,
  },
  {
    key: 3,
    value: 20,
  },
  {
    id: 123,
    value: 30,
  },
  {
    id: 123,
    value: 30,
  },
  {
    id: 123,
    value: 30,
  },
  {
    id: 123,
    value: 30,
  },
];

// 只能给指定索引添加的代码
const add = function(i) {
    arrayofObj[i].val = array1[i] 
}

add(2)

期望效果:

const arrayofObj = [
  {
    key:1,
    value:3,
    val: 1 // array1[0]
  },
  {
    key:2,
    value:10,
    val: 2 // array1[1]
  },
  // ... 其余对象同理
]
解决方案

方法1:直接修改原数组(使用forEach)

遍历arrayofObj,给每个对象添加val属性,值取array1对应索引的元素。如果array1长度比arrayofObj短,超出索引的val会设为undefined。

arrayofObj.forEach((obj, index) => {
  obj.val = array1[index];
});

方法2:返回新数组(不修改原数组,使用map)

如果不想改动原数组,可以用map生成一个新的对象数组,每个对象包含原属性和新增的val:

const newArrayOfObj = arrayofObj.map((obj, index) => {
  // 展开原对象,添加val属性,避免修改原对象
  return { ...obj, val: array1[index] };
});

方法3:处理数组长度不一致的情况

如果想给array1没有对应值的对象设置默认值(比如null或0),可以在赋值时做判断:

arrayofObj.forEach((obj, index) => {
  obj.val = array1[index] ?? null; // 使用null作为默认值,也可以换成0或其他
});

内容的提问来源于stack exchange,提问作者tomaszM-dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 23:40:04