批量排除对象的指定字段

3 阅读1分钟
/**
 * 批量排除对象的指定字段(基于 Object.fromEntries 实现)
 * @param {Object} obj - 源对象(非对象类型会返回原值并警告)
 * @param {string[]} excludeKeys - 需要排除的字段名数组(非数组会返回原对象浅拷贝并警告)
 * @returns {Object} 排除指定字段后的新对象(浅拷贝)
 */
export function excludeObjectFields(obj:Record<string,any>, excludeKeys:string[] = []) {
  // 校验源对象:如果不是有效对象(null/非对象类型),返回原值并提示
  if (typeof obj !== 'object' || obj === null) {
    console.warn('excludeObjectFields: 第一个参数必须是有效对象');
    return obj;
  }

  // 校验排除字段数组:如果不是数组,返回原对象浅拷贝并提示
  if (!Array.isArray(excludeKeys)) {
    console.warn('excludeObjectFields: 第二个参数必须是字符串数组');
    return { ...obj };
  }

  // 核心逻辑:转entries → 过滤 → 转回对象
  return Object.fromEntries(
    // 过滤掉excludeKeys中包含的key
    Object.entries(obj).filter(([key]) => !excludeKeys.includes(key))
  );
}