Delete null values in nested javascript objects

a 夏天 提交于 2019-12-24 19:43:11

问题


I have a nested object and want to remove all key/value pairs if the value is null or undefined. I've managed to get the below code working but it doesn't check the nested key/value pairs and wondered if someone could help me figure out what needs adding to the code please?

var myObj = {
  fName:'john',
  lName:'doe',
  dob:{
    displayValue: null, 
    value: null
  },
  bbb:null
};

function clean(obj) {
  for (var propName in obj) { 
    if (obj[propName] === null || obj[propName] === undefined || obj[propName] === '') {
      delete obj[propName];
    }
  }
  return obj;
}
console.log(clean(myObj));

The above code does the job to remove 'bbb' and its value and I want the same done for the nested object represented by 'dob' as well.

https://jsbin.com/mudirateso/edit?js,console,output

Any help is greatly appreciated.


回答1:


You're already almost there. Just have the function recurse if the property is another object:

var myObj = {
  fName:'john',
  lName:'doe',
  dob:{
    displayValue: null, 
    value: null
  },
  bbb:null
};

function clean(obj) {
  for (var propName in obj) { 
    if (obj[propName] === null || obj[propName] === undefined || obj[propName] === '') {
      delete obj[propName];
    } else if (typeof obj[propName] === "object") {
      // Recurse here if the property is another object.
      clean(obj[propName])
    }
  }
  return obj;
}
console.log(clean(myObj));


来源:https://stackoverflow.com/questions/47296396/delete-null-values-in-nested-javascript-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!