删除对象中为空的值,包括数组和对象

107 阅读1分钟
  static isArray(data) {
    return Object.prototype.toString.call(data) === '[object Array]';
  }
  static isObject(data) {
    return Object.prototype.toString.call(data) === '[object Object]';
  }
  static isNumber(data) {
    return Object.prototype.toString.call(data) === '[object Number]';
  }
  static isString(data) {
    return Object.prototype.toString.call(data) === '[object String]';
  }
  static isUndefined(data) {
    return Object.prototype.toString.call(data) === '[object Undefined]';
  }
  static isNull(data) {
    return Object.prototype.toString.call(data) === '[object Null]';
  }
  // 获取一个数据的数据类型
  static getType(data) {
    return Object.prototype.toString
      .call(data)
      .split(' ')[1]
      .slice(0, -1);
  }

  // 删除对象中为空的值,包括数组和对象
  static removeEmptyValue(obj) {
    for (const key in obj) {
      if (Object.hasOwnProperty.call(obj, key)) {
        const element = obj[key];
        if (!element) {
          delete obj[key];
        } else {
          if (this.isObject(element)) {
            if (JSON.stringify(element) === '{}') {
              delete obj[key];
            }
          }
          if (this.isArray(element)) {
            if (element.length === 0) {
              delete obj[key];
            }
          }
        }
      }
    }
    return obj;
  }