this is my object . I am trying to remove empty array, empty string,null, undefined.
let result = {
a : [],
b: undefined,
c: null,
d: NaN,
e: {},
f:{test: undefined, tes1: null,tes2:NaN},
g:{name :{x:undefined, y:"s", z: null}},
x:"sujon",
y:"",
}
Now, I can only delete the undefined value from an object by using this code;
const removeEmpty = (obj) => {
Object.keys(obj).forEach(key => {
if (obj[key] && typeof obj[key] === 'object') removeEmpty(obj[key]);
else if (obj[key] === undefined) delete obj[key];
});
return obj;
};
let res = removeEmpty(result)
console.log(res)
my expected result would be like this:
let result = {
g:{name :{y:"s"}},
x:"sujon",
}
How can i get my expected result?
After the recursive call, if the result is an empty object (with no own-properties), remove it:
let result = { a : [], b: undefined, c: null, d: NaN, e: {}, f:{test: undefined, tes1: null,tes2:NaN}, g:{name :{x:undefined, y:"s", z: null}}, x:"sujon", y:"", z:0, } const removeEmpty = (obj) => { Object.keys(obj).forEach(key => { if (obj[key] && typeof obj[key] === 'object') removeEmpty(obj[key]); if ( (!obj[key] && obj[key] !== 0) || (typeof obj[key] === 'object' && Object.keys(obj[key]).length === 0) ) { delete obj[key]; } }); return obj; }; let res = removeEmpty(result) console.log(res)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.