Skip to main content

替换对象空属性

/** * 替换对象空属性 * @param obj 对象 * @param content 替换后的内容 * @param recursive 是否递归替换 (如果遇到数组,性能消耗较大) */export function replaceEmptyProperty(obj?: any, content: any = '', recursive = false): AnyObj {  if (!obj) return {}  const newObj = {}  for (const key in obj) {    const val = obj[key]    if ([null, undefined, ''].includes(val)) {      newObj[key] = content    } else if (recursive && typeof val === 'object') {      if (Array.isArray(val)) {        newObj[key] = val.map((v) => replaceEmptyProperty(v, content, recursive))      } else {        newObj[key] = replaceEmptyProperty(val, content, recursive)      }    }  }  return Object.assign({}, obj, newObj)}
/** * 替换对象空属性 (数组) * @param arr 数组 * @param content 替换后的内容 * @param recursive 是否递归替换 (如果遇到数组,性能消耗较大) */export function replaceEmptyPropertyArray(arr?: any[], content: any = '', recursive = false): any[] {  if (!arr) return []  return arr.map((v) => {    if (Array.isArray(v)) {      return replaceEmptyPropertyArray(v, content, recursive)    } else {      return replaceEmptyProperty(v, content, recursive)    }  })}