如何给数组对象中每一项都新增某属性

文章介绍了在JavaScript中使用map和forEach方法处理数组的不同方式。map方法用于创建新数组,不改变原数据,而forEach则直接修改原数组,无返回值。示例中展示了如何添加新属性并应用颜色数组到对象列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 方法一:map()

map()方法 返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

注意:为了不影响原对象数据,所以对属性进行拷贝(...item)

const dataList = [
    {
      name:'小芳',
      age: 18
    },
    {
      name:'小花',
      age: 19
    }
  ]
 const cList = ['#FFA822', '#C215F9'];
  const newList = dataList.map((item,index)=>{
    return {
      ...item,
      sex:'女',
      itemStyle: {
        color: cList[index],
      },
    }
  })
  console.log(newList,'newList',dataList);

 方法二: foreach() 方法 :

foreach()方法  用于调用数组的每个元素,并将元素传递给回调函数。

注意:该方法会直接改变原数组,无返回值

const dataList = [
    {
      name:'小芳',
      age: 18
    },
    {
      name:'小花',
      age: 19
    }
  ]
  const cList = ['#FFA822', '#C215F9'];
  const newList = dataList?.forEach((item, index) => {
    item.sex = '女'
    item.itemStyle = {
      color: cList[index]
    }
  })
  console.log(newList, 'newList', dataList);

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值