Created
March 20, 2024 09:58
-
-
Save av1v3k/b1ae216da059a1ec03d41a3cb2a0f8d3 to your computer and use it in GitHub Desktop.
remove undefined, empty string, empty array key values in Object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function deepCopy(obj) { | |
if (typeof obj !== 'object' || obj === null) { | |
return obj; // Return primitive values and null as is | |
} | |
const copy = Array.isArray(obj) ? [] : {}; | |
for (let key in obj) { | |
copy[key] = deepCopy(obj[key]); | |
} | |
return copy; | |
} | |
function loopNestedObjectsAndRemoveEmpty(obj) { | |
for (let key in obj) { | |
if (Object.prototype.toString.call(obj[key]) === '[object Object]' && obj[key] !== null) { | |
loopNestedObjectsAndRemoveEmpty(obj[key]); | |
} else { | |
if (Object.prototype.toString.call(obj[key]) === '[object Array]' && obj[key].length === 0) { | |
delete obj[key]; | |
} else if (obj[key] === '') { | |
delete obj[key]; | |
} | |
} | |
} | |
return obj; | |
} | |
const obj1 = { | |
hello: { | |
age: 45, | |
pass: '', | |
creek: '', | |
address: { | |
street: '12, jakdsf street', | |
city: '', | |
pincode: [], | |
}, | |
}, | |
}; | |
const retObj = loopNestedObjectsAndRemoveEmpty(deepCopy(obj1)); | |
console.log(retObj); | |
console.log(obj1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment