数组常用操作

4 阅读1分钟

给数组中新增一个属性

const array = [
  { id: 1, name: 'item1' },
  { id: 2, name: 'item2' },
  { id: 3, name: 'item3' }
];

// 改变原数组
array.forEach(item => {
  item.is_active = 1;
});

// 不改变原数组
const newArray = array.map(item => ({
  ...item,
  is_active: 1
}));

删除数组中的属性

const array = [
  { id: 1, name: 'item1', price: 100, category: 'A' },
  { id: 2, name: 'item2', price: 200, category: 'B' },
  { id: 3, name: 'item3', price: 300, category: 'C' }
];

// 要删除的属性名
const propertiesToDelete = ['price', 'category'];

// 改变原数组
array.forEach(item => {
  propertiesToDelete.forEach(prop => {
    delete item[prop];
  });
});

// 不改变原数组
const newArray = array.map(({ price, category, ...rest }) => rest);

修改数组中的属性

const array = [
  { id: 1, name: 'item1', price: 100, category: 'A' },
  { id: 2, name: 'item2', price: 200, category: 'B' },
  { id: 3, name: 'item3', price: 300, category: 'C' }
];

const updatedArray = array.map(item => ({
  ...item,
  name: 'zzz'
}));

删除又新增

const array = [
  { id: 1, name: 'item1', price: 100, category: 'A' },
  { id: 2, name: 'item2', price: 200, category: 'B' },
  { id: 3, name: 'item3', price: 300, category: 'C' }
];

// 要删除的属性名
const propertiesToDelete = ['price', 'category'];

// 改变原数组
array.forEach(item => {
  // 删除指定的属性
  propertiesToDelete.forEach(prop => {
    delete item[prop];
  });
  
  // 新增属性
  item.is_available = true;
});

// 不改变原数组
const newArray = array.map(item => {
  // 创建对象的副本
  const newItem = { ...item, is_available: true };
  
  // 删除指定的属性
  propertiesToDelete.forEach(prop => {
    delete newItem[prop];
  });
  
  return newItem;
});