Skip to content
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

Open
Sunny-117 opened this issue Nov 3, 2022 · 3 comments
Open

移除空属性 #101

Sunny-117 opened this issue Nov 3, 2022 · 3 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@mengqiuleo
Copy link

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:'哈哈哈'}

@veneno-o
Copy link
Contributor

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;
}

@kangkang123269
Copy link

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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants