js对象数组浅复制且赋新值的几种方法

const a1 = [{a:'a'}, {b:'b'}];

// 示例1:使用扩展运算符复制对象并添加新属性
const a2 = a1.map((item, index) => ({
  ...item,               // 复制原对象属性
  id: index,             // 新增id属性
  timestamp: Date.now()  // 新增时间戳属性
}));

// 示例2:使用Object.assign复制并覆盖原有属性(如有)
const a3 = a1.map((item, index) => Object.assign(
  {},                    // 目标空对象
  item,                  // 复制原对象属性
  { 
    index: index + 1,    // 新增index属性(值为索引+1)
    active: true         // 新增active属性
  }
));

// 示例3:条件性添加属性(根据原对象内容判断)
const a4 = a1.map(item => {
  // 复制原对象
  const newItem = { ...item };
  
  // 根据原对象属性添加新值
  if (newItem.a) {
    newItem.a = newItem.a.toUpperCase(); // 转换为大写
    newItem.type = 'A类';
  } else if (newItem.b) {
    newItem.b = newItem.b.repeat(2);     // 重复字符串
    newItem.type = 'B类';
  }
  
  return newItem;
});

// 示例4:添加嵌套属性(不影响原对象的嵌套结构)
const a5 = a1.map((item, index) => ({
  ...item,
  meta: {                // 新增嵌套对象
    position: index,
    source: 'original'
  }
}));

// 输出结果验证(原数组a1保持不变)
console.log('原数组a1:', JSON.stringify(a1));
console.log('示例1 a2:', JSON.stringify(a2));
console.log('示例2 a3:', JSON.stringify(a3));
console.log('示例3 a4:', JSON.stringify(a4));
console.log('示例4 a5:', JSON.stringify(a5));

 

posted on 2025-08-05 15:09  骑着母猪去打猎  阅读(15)  评论(0)    收藏  举报