如何删除JavaScript对象中未定义或空的所有属性?

(这个问题与数组的问题类似)


当前回答

如果你不想原地改变,而是返回一个删除了null/undefined的克隆,你可以使用ES6的reduce函数。

// Helper to remove undefined or null properties from an object
function removeEmpty(obj) {
  // Protect against null/undefined object passed in
  return Object.keys(obj || {}).reduce((x, k) => {
    // Check for null or undefined
    if (obj[k] != null) {
      x[k] = obj[k];
    }
    return x;
  }, {});
}

其他回答

var testObject = { test1:“零”, test2:空, test3:“somestring”, test4: 3, test5:“定义”, test6:未定义的, } 函数removeObjectItem (obj) { For (var key in obj) { 如果(String (obj(例子))= = =“零”| |字符串(obj(例子))= = =“定义”){ 删除obj(例子); } } 返回obj } console.log (removeObjectItem (testObject))

这个问题已经被彻底回答了,我只是想根据其他例子贡献我的版本:

function filterObject(obj, filter) {
    return Object.entries(obj)
        .map(([key, value]) => {
            return [key, value && typeof value === 'object'
                ? filterObject(value, filter)
                : value];
        })
        .reduce((acc, [key, value]) => {
            if (!filter.includes(value)) {
                acc[key] = value;
            }

            return acc;
        }, {});
}

这个解决方案的不同之处在于,你可以在第二个参数中指定你想要过滤的值,如下所示:

const filtered = filterObject(originalObject, [null, '']);

它将返回一个新对象(不改变原始对象),不包括值为null或”的属性。

您可以使用JSON的组合。stringify,它的替换参数,以及JSON。解析将其转换回对象。使用此方法还意味着替换嵌套对象中的所有嵌套键。

实例对象

var exampleObject = {
  string: 'value',
  emptyString: '',
  integer: 0,
  nullValue: null,
  array: [1, 2, 3],
  object: {
    string: 'value',
    emptyString: '',
    integer: 0,
    nullValue: null,
    array: [1, 2, 3]
  },
  arrayOfObjects: [
    {
      string: 'value',
      emptyString: '',
      integer: 0,
      nullValue: null,
      array: [1, 2, 3]
    },
    {
      string: 'value',
      emptyString: '',
      integer: 0,
      nullValue: null,
      array: [1, 2, 3]
    }
  ]
};

替代者函数

function replaceUndefinedOrNull(key, value) {
  if (value === null || value === undefined) {
    return undefined;
  }

  return value;
}

清洁物体

exampleObject = JSON.stringify(exampleObject, replaceUndefinedOrNull);
exampleObject = JSON.parse(exampleObject);

CodePen例子

TypeScript的泛型函数

function cleanProps(object:Record<string, string>):Record<string, string> {
  let cleanObj = {};

  Object.keys(object).forEach((key) => {
    const property = object[key];
    cleanObj = property ? { ...cleanObj, [key]: property } : cleanObj;
  });

  return cleanObj;
}

export default cleanProps;

现在假设你有一个像下面这样的对象

interface Filters{
 searchString: string;
 location: string;
 sector: string
}

const filters:Filters = {
  searchString: 'cute cats',
  location: '',
  sector: 'education',
};

您可以按照如下方式使用该函数

const result = cleanProps(filters as Record<keyof Filters, string>);
console.log(result); // outputs: { searchString: 'cute cats', sector: 'education' }

删除所有带有null和undefined的属性

让obj = { “id”:1、 “firstName”:空, “姓”:空, “地址”:未定义的, “角色”:“客户”, “照片”:“fb79fd5d - 06 - c9 - 4097 - 8 fdc - 6 - cebf73fab26 / fc8efe82-2af4-4c81-bde7-8d2f9dd7994a.jpg”, “位置”:空, “idNumber”:空, }; let result = Object.entries(obj).reduce((a,[k,v]) => (v == null ?A: (A [k]=v, A)), {}); console.log(结果)