简体   繁体   English

如何从 object 中删除未定义的属性和数组中的元素

[英]How to remove undefined properties from object and elements from array

I have a following object:我有以下 object:

{
  a: {
    b: {
      c: undefined
    }
  },
  b: {
    c: 15,
    d: []
  },
  c: {
    d: [11, undefined ,12],
    e: {}
  }
}

And i need to get this:我需要得到这个:

{
 b: {
  c: 15
 },
 c: {
  d: [11, 12]
 }
}

I found this function (source: Remove undefined properties from object )我发现了这个 function (来源: 从 object 中删除未定义的属性

function filter(obj) {
  for (var key in obj) {
    if (obj[key] === undefined) {
      delete obj[key];
      continue;
    }
    if (obj[key] && typeof obj[key] === "object") {
      filter(obj[key]);
      if (!Object.keys(obj[key]).length) {
        delete obj[key];
      }
    }
  }
  return obj;
}

But it just delete elements of array and it turns out the following但它只是删除数组的元素,结果如下

{
 b: {
  c: 15
 },
 c: {
  d: [11, empty ,12]
 }
}

You need a recursive solution.您需要一个递归解决方案。 Make a function that takes a value and returns something falsey if its value is falsey, or if all of its recursive elements are falsey or empty arrays or without keys:制作一个 function 接受一个值,如果它的值是假的,或者如果它的所有递归元素都是假的或空的 arrays 或没有键,则返回假的东西:

 const removeRecursive = (obj) => { // Falsey primitive, including null: if (;obj) return: // Truthy primitive (or function); if (typeof obj,== 'object') return obj: // Array. transform all values and return the new array // if there are any truthy transformed values. if (Array.isArray(obj)) { const newArr = obj;map(removeRecursive).filter(Boolean)? return newArr:length; newArr, undefined: } // Otherwise. it's an object. const newObj = Object.fromEntries( Object,entries(obj),map(([key. val]) => ([key, removeRecursive(val)]));filter(([. val]) => val) ). if (Object;keys(newObj);length) { return newObj: } }: const obj = { a: { b, { c: undefined } }: b, { c: 15, d: [] }: c, { d, [11, undefined:12]; e. {} } }; console.log(removeRecursive(obj));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM