-
-
Notifications
You must be signed in to change notification settings - Fork 229
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
移除空属性 #101
Comments
let obj={a:null,b:'哈哈哈'}
//对象移除为空的属性
for (const [key, value] of Object.entries(obj)) {
if (value === null || value === "" || value === undefined) { //筛选条件可根据实际情况自行调整
Reflect.deleteProperty(obj, key);
}
}
console.log(obj) //{b:'哈哈哈'} |
function main(obj){
for (const key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
if(obj[key] === null || obj[key] === undefined || obj[key] === ""){
delete obj[key]
}else if(typeof obj[key] === "object"){
main(obj[key])
}
}
}
return obj;
} |
function removeEmpty(obj) {
Object.keys(obj).forEach(key =>
(obj[key] && typeof obj[key] === 'object') && removeEmpty(obj[key]) ||
(obj[key] === undefined || obj[key] == null || obj[key] === '') && delete obj[key]
);
return obj;
};
let myObj = { a: '', b: null, c: undefined, d: 'Hello', e: { f: '', g:'World' } };
console.log(removeEmpty(myObj)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: