How to delete recursively undefined properties from an object - while keeping the constructor chain?

前端 未结 4 2438
醉酒成梦
醉酒成梦 2021-02-20 14:01

This is a question similar to How to remove undefined and null values from an object using lodash?. However, the solutions proposed there do not conserve the constructor. In add

4条回答
  •  说谎
    说谎 (楼主)
    2021-02-20 14:25

    You can use JSON.stringify(), JSON.parse(), RegExp.prototype.test()

    JSON.parse(JSON.stringify(obj, function(a, b) {
      if (!/^_/.test(a) && b === undefined) {
        return null
      }
      return /^_/.test(a) && !b ? void 0 : b
    }).replace(/null/g, '"undefined"'));
    

    var obj = {key1 : 'value1', key2 : {key21 : 'value21', _key22: undefined}, key3: undefined, _key4 : undefined}
    
    var res = JSON.stringify(obj, function(a, b) {
      if (!/^_/.test(a) && b === undefined) {
        return null
      }
      return /^_/.test(a) && !b ? void 0 : b
    }).replace(/null/g, '"undefined"');
    
    document.querySelector("pre").textContent = res;
    
    res = JSON.parse(res);
    
    console.log(res)

提交回复
热议问题