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

如何用TypeScript编写按指定key新增或替换对象数组元素的函数

调整后支持自定义比对键的函数实现
export function addOrReplaceByKey<T extends object, K extends keyof T & (string | number)>(
  arrayOfObjects: T[],
  newObject: T,
  compareKey: K
): T[] {
  const index = arrayOfObjects.findIndex(
    (item) => item[compareKey] === newObject[compareKey]
  );

  if (index === -1) {
    arrayOfObjects.unshift(newObject);
  } else {
    arrayOfObjects[index] = newObject;
  }
  return arrayOfObjects;
}

核心改动说明

  • 新增第三个入参compareKey:作为自定义比对的属性键,通过泛型约束K extends keyof T & (string | number)确保只能传入数组元素对象存在、且键名类型为string/number的合法属性,完全匹配需求
  • 移除硬编码的id属性依赖:泛型不再要求对象必须包含id字段,适配任意结构的对象数组
  • 动态比对逻辑:将原固定的id等值判断改为基于传入的compareKey取对应值进行比对,实现灵活的替换/新增逻辑

使用示例

// 示例:基于自定义键userId比对
interface Goods {
  userId: number;
  goodsName: string;
  price: number;
}
const goodsList: Goods[] = [
  { userId: 101, goodsName: '笔记本', price: 5999 },
  { userId: 102, goodsName: '鼠标', price: 99 }
];

// 新增对象:找不到匹配userId,插入数组首位
addOrReplaceByKey(goodsList, { userId: 103, goodsName: '键盘', price: 299 }, 'userId');
// 替换对象:匹配到userId=102的对象,原位置替换
addOrReplaceByKey(goodsList, { userId: 102, goodsName: '无线鼠标', price: 129 }, 'userId');

提示:当前实现和你原有代码逻辑一致,会直接修改传入的原数组。如果需要不修改原数组的不可变实现,可使用以下版本:

export function addOrReplaceByKeyImmutable<T extends object, K extends keyof T & (string | number)>(
  arrayOfObjects: T[],
  newObject: T,
  compareKey: K
): T[] {
  const index = arrayOfObjects.findIndex(item => item[compareKey] === newObject[compareKey]);
  if (index === -1) {
    return [newObject, ...arrayOfObjects];
  }
  return [
    ...arrayOfObjects.slice(0, index),
    newObject,
    ...arrayOfObjects.slice(index + 1)
  ];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 21:51:01