从对象中删除未定义的属性

时间:2017-07-06 15:58:06

标签: javascript object recursion undefined

我想以递归方式清除任何未定义的字段,或者将空对象作为父对象,如下所示:

示例:

{
  "a": {
    "b": {
      "c": undefined,
    }
  },
  "d": undefined,
  "e": {
    f: undefined,
  },
  "g": {
     "h": 'I',
     "j": undefined,
  },
  "k": "L",
  "m": {
     "n": {
       "o": {
         "z": undefined,
       }
     },
    "p": 'toto'
   }
}

我期待以下结果:

{
  "g": {
    "h": 'I',
  },
  "k": 'L',
  "m": {
    "p": 'toto'
  }
}

感谢您的帮助

2 个答案:

答案 0 :(得分:1)



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;
}

var data = {
  "a": {
    "b": {
      "c": undefined,
    }
  },
  "d": undefined,
  "e": {
    "f": undefined,
  },
  "g": {
    "h": 'I',
    "j": undefined,
  },
  "k": "L",
  "m": {
    "n": {
      "o": {
        "z": undefined,
      }
    },
    "p": 'toto'
  }
};

console.log(filter(data));




只需删除这些键并递归迭代。

答案 1 :(得分:1)

function cleanArray(actual) {
  var newArray = new Object();
 newArray=JSON.parse(JSON.stringify(actual));
  return newArray;
}
var obj={
  "a": {
    "b": {
      "c": undefined,
    }
  },
  "d": undefined,
  "e": {
    f: undefined,
  },
  "g": {
     "h": 'I',
     "j": undefined,
  },
  "k": "L",
  "m": {
     "n": {
       "o": {
         "z": undefined,
       }
     },
    "p": 'toto'
   }
};
console.log(cleanArray(obj));