javascript 从嵌套对象中删除空值和null值(ES6)-清除嵌套对象

ilmyapht  于 2022-12-10  发布在  Java
关注(0)|答案(9)|浏览(252)

我得到了一个对象,它看起来像这样:

{
    "a": "string not empty",
    "b": {
        "c": "string not empty",       
    },
    "d": {
        "e": false,
        "f": 0,
        "g": true,
        "h": 10
    },
    "i": {
        "j": 0,
        "k": null
    },
    "l": {
        "m": null
    },
    "n": {
        "o": 1,
        "p": "string (not empty)",
        "q": {}
    },
    "r": [],
    "l": "2000-01-01T01:01:00.000Z",
}

感谢此处提供的代码:https://stackoverflow.com/a/38364486/3912805我现在可以删除嵌套对象的所有null值。
到目前为止,我对removeNull使用了此函数:

removeNull = (obj) => {
  Object.keys(obj).forEach(key =>
    (obj[key] && typeof obj[key] === 'object') && removeNull(obj[key]) ||
    (obj[key] === undefined || obj[key] === null) && delete obj[key]
  );
  return obj;
};

但是我想增强这个函数,允许我删除所有空数组或任何可能存在于我的嵌套对象中的空集合。
最终结果应为 * 不含 * klmqrl

{
    "a": "string not empty",
    "b": {
        "c": "string not empty",       
    },
    "d": {
        "e": false,
        "f": 0,
        "g": true,
        "h": 10
    },
    "i": {
        "j": 0
    },
    "n": {
        "o": 1,
        "p": "string (not empty)"
    },
    "l": "2000-01-01T01:01:00.000Z",
}

我需要保留所有设置为0false的值。
我想使用ES6方法增强这个removeNull的方法,但是到目前为止我还没有做到。
我还尝试了用于此How to deeply remove null values, empty objects and empty array from an object的老方法

itemToBool = item => {
  if (typeof item !== 'object' || item === null) return item;
  const cleanedItem = cleanObject(item);
  return Object.keys(cleanedItem).length !== 0 && cleanedItem;
};

cleanObject = obj => {
  if (Array.isArray(obj)) {
    const newArr = obj.map(itemToBool).filter(Boolean);
    return newArr.length && newArr;
  }
  const newObj = Object.entries(obj).reduce((a, [key, val]) => {
    const newVal = itemToBool(val);
    if (newVal !== null || newVal === false) a[key] = newVal;
    return a;
  }, {});
  return Object.keys(newObj).length > 0 && newObj;
};

但也失败了。

f3temu5u

f3temu5u1#

您可以采取直接的方法,即迭代对象的键/值对,首先迭代嵌套的可迭代对象,然后删除不需要的键。
第一个

krcsximq

krcsximq2#

您可以利用JSON.stringify及其可选的第二个参数replacer,但请注意以下代码会删除null * 和 * undefined

const sanitize = (obj) => {
  return JSON.parse(JSON.stringify(obj, (key, value) => {
    return (value === null ? undefined : value);
  }));
};

const obj = {
  "a": "string not empty",
  "b": {
    "c": "string not empty",
  },
  "d": {
    "e": false,
    "f": 0,
    "g": true,
    "h": 10
  },
  "i": {
    "j": 0,
    "k": null
  },
  "l": {
    "m": null
  },
  "n": {
    "o": 1,
    "p": "string (not empty)",
    "q": {}
  },
  "r": [],
  "l": "2000-01-01T01:01:00.000Z",
}

console.log(sanitize(obj))
hfyxw5xn

hfyxw5xn3#

感谢尼娜·肖尔茨,我的增强版将是:

cleanObject = function(object) {
    Object
        .entries(object)
        .forEach(([k, v]) => {
            if (v && typeof v === 'object')
                cleanObject(v);
            if (v && 
                typeof v === 'object' && 
                !Object.keys(v).length || 
                v === null || 
                v === undefined ||
                v.length === 0
            ) {
                if (Array.isArray(object))
                    object.splice(k, 1);
                else if (!(v instanceof Date))
                    delete object[k];
            }
        });
    return object;
}
doinxwow

doinxwow4#

如果你不想改变对象,需要一个新的副本,那么你可以将对象字符串化为json并解析它,在解析的时候过滤。如果你不需要源对象,那么你可以覆盖结果到相同的引用中。这可能不是一个性能高效的方法,但显然更干净,也不是一个自递归的方法。

var obj = {
    "a": "string not empty",
    "b": {
        "c": "string not empty",       
    },
    "d": {
        "e": false,
        "f": 0,
        "g": true,
        "h": 10
    },
    "i": {
        "j": 0,
        "k": null
    },
    "l": {
        "m": null
    },
    "n": {
        "o": 1,
        "p": "string (not empty)",
        "q": {}
    },
    "r": [],
    "s": {"t": null},
    "u": [null, {"v": {}}]
}
function copyNonEmpty(o) {
  let ignores = [null, undefined, ""],
    isNonEmpty = d => !ignores.includes(d) && (typeof(d) !== "object" || Object.keys(d).length)
  return JSON.parse(JSON.stringify(o), function(k, v) {
    if (isNonEmpty(v))
      return v;
  });
}

var res = copyNonEmpty(obj);
console.log(JSON.stringify(res, null, 4));

如果值为ObjectArray,则typeof将返回objectObject.keys将返回两种情况下的键数组("0", "1"2 ...如果是数组),以及数组长度如果它是一个空数组或对象,则(键的)将为0。因此,有条件地,它将不能(nullundefined"")和(非object/arrayORobject/array,它是非空的,然后您可以获取该值。

igetnqfo

igetnqfo5#

若要移除空数组、字串、null、未定义的值

function removeEmptyElements(obj) {
  if (Array.isArray(obj)) {
    obj.forEach((element, index) => obj.splice(index, 1, removeEmptyElements(element)));
    return obj;
  }
  return Object.fromEntries(Object.entries(obj)
    .filter(([, v]) => (Array.isArray(v) ? v.length !== 0 : (v !== null && v !== '' && v !== undefined)))
    .map(([k, v]) => [k, v === (Object(v)) ? removeEmptyElements(v) : v]));
}
soat7uwm

soat7uwm6#

我刚刚解决了同样的问题,所以我想和大家分享一下。我的代码也清理了嵌套对象和数组,可以根据你的要求进行定制:

cleanObject = (input) => {
  if (typeof input === 'object' && input !== null) {
    if(Array.isArray(input)) {
      return input.map(cleanObject)
                  .filter(item => item !== null && item !== undefined) 
    }

    return Object.fromEntries(
      Object.entries(input)
            .map(([key, val]) => [key, cleanObject(val)])
            .filter(([k, v]) => v !== null && v !== undefined)
    );

  } 

  return input;
}
// testcase:
 const testVal = {
  a: 1,
  b: 2,
  c: undefined,
  d: { a: 99, b: null },
  e: { a: 1, b: 2, d: undefined, g: null, e: 0 },
  f: [1, 0, null, undefined],
  g: [1, 2],
  h: { aa: 1, bb: { c: 1, d: [111, null], e: 'hello' } },
};

cleanObject(testVal);
sbdsn5lh

sbdsn5lh7#

我试了一下

const test = {
       a: '',
       b: 1,
       c: [],
       d: {
        e: null,
        f: 0,
        g: undefined,
        h: {
            i: 'test',
            j: {},
            k: '',
            l: {
                m: 'yo test',
                n: 'go for it'
            }
        }
     },
    e: 'yo tested'
    };

    const JS_PRIMITIVE_TYPES = { 'string': 1, 'number': 1, 'undefined': 1, 'boolean': 1, 
    'symbol': 1 }

    const isValuePrimitiveType = (value) => {
    const typeOfVal = typeof value;
    if (JS_PRIMITIVE_TYPES.hasOwnProperty(typeOfVal)) {
        return true;
    }
    return false;
    }

    /* MAIN Function which runs and call other functions
       allKeys : keys of object Object.keys(test);
       badJson : json which needs to be update
    */
      const iterateObjForRemoveEmptyElem = (badJson, allKeys) => {
       for (let index = 0; index < allKeys.length; index++) {
          const key = allKeys[index];
          if (isEmpty(badJson[key])) {
             delete badJson[key];
          } else if (Array.isArray(badJson[key]) || isValuePrimitiveType(badJson[key])) {
            continue;
         }
         else {
            const newKeys = Object.keys(badJson[key]);
            const newJson = Object.assign({}, badJson[key]);
            badJson[key] = iterateObjForRemoveEmptyElem(newJson, newKeys);
        }
    }
    return badJson;
    }


    const isEmpty = (val) => {
     if(val === '' || val === null || val === undefined ) {
         return true;
     } else if (Array.isArray(val) && val.length === 0){
        return true;
     } else if(typeof val === 'object' && Object.keys(val).length === 0){
        return true;
     }
    return false;
    }

    const myKeys = Object.keys(test);
    console.log("Final Result:::::",JSON.stringify(iterateObjForRemoveEmptyElem(test,myKeys)));

这对我来说最高可达第n级

oewdyzsn

oewdyzsn8#

function cleanObject(obj: object) {
  // remove all keys with undefined values in nested objects
  const cleaned = Object.entries(obj).reduce((acc, [key, val]) => {
    if (val && typeof val === 'object') {
      val = cleanObject(val);
    }
    if (val !== undefined) {
      acc[key] = val;
    }
    return acc;
  }, {});
  return cleaned;
}
const data = {
  a: 50,
  b: 90,
  c: undefined,
  d: undefined,
  e: {
    a: 90,
    b: 80,
    c: undefined,
    d: undefined,
  },
  f: {
    a: undefined,
    b: undefined,
    c: undefined,
    d: undefined,
  },
};

console.log(cleanObject(data));

输出=〉{ a:50,B:90,戊:{甲:90,B:80 },f:{} }

3phpmpom

3phpmpom9#

//sample Json Response
var items = {
            name: 'test',
            randomArray: [],
             randomObject: {
                id: null,
                someObject: {},
                someInternalArray: [],
                someUndefinedObject: undefined,
            },
              New name: null,
               nestedObject: [
                {
                      emp: {
                        id: null,
                    },
                   empAssets: 2,
                   joiningDate: {
                        startDate: null,
                        endDate: '2019/12/01',
                         Addresses: [],
                    },
                },
            ],
        };
       this.removeEmptyKeys(items);
        console.log('the final items ‘,items);

//Removing logic 
removeEmptyKeys(yourObject) {
        Object.keys(yourObject).forEach(key => {
            if (
                Object.prototype.toString.call(yourObject[key]) === '[object Date]' &&
                (yourObject[key].toString().length === 0 ||
                    yourObject[key].toString() === 'Invalid Date')
            ) {
                delete yourObject[key];
            } else if (yourObject[key] && typeof yourObject[key] === 'object') {
                this.removeEmptyKeysFromObject(yourObject[key]);
            } else if (yourObject[key] == null || yourObject[key] === '') {
                delete yourObject[key];
            }

            if (
                yourObject[key] &&
                typeof yourObject[key] === 'object' &&
                Object.keys(yourObject[key]).length === 0 &&
                Object.prototype.toString.call(yourObject[key]) !== '[object Date]'
            ) {
                delete yourObject[key];
            }
        });
        return yourObject;
    }

移除未定义、null、空字串、空数组。如果有帮助,请投赞成票。

相关问题