8

How to remove all blank Objects from an Object in Javascript? Like this

const test={a:'a',b:{},c:{c:{}}}

How to get result:

test={a:'a'}
0

2 Answers 2

4

The below recursive function will remove all empty objects.

function removeEmpty(obj) {
 Object.keys(obj).forEach(k => {
 if (obj[k] && typeof obj[k] === 'object' && removeEmpty(obj[k]) === null) {
 delete obj[k];
 }
 });
 if (!Object.keys(obj).length) {
 return null;
 }
}

Working Demo

function removeEmpty(obj) {
 Object.keys(obj).forEach(k => {
 if (obj[k] && typeof obj[k] === 'object' && removeEmpty(obj[k]) === null) {
 delete obj[k];
 }
 });
 if (!Object.keys(obj).length) {
 return null;
 }
}
const test1 = {data:{a:{}}};
removeEmpty(test1);
console.log(test1); // {}
const test2 = {data:{a:{}, b:1}};
removeEmpty(test2);
console.log(test2); // {data:{b: 1}}
const test3 = {a:'a',b:{},c:{c:{}}};
removeEmpty(test3);
console.log(test3); // {a: 'a'}

answered Aug 16, 2020 at 2:56
Sign up to request clarification or add additional context in comments.

Comments

0

Here is another way with some details.

Needs/To keep in mind:

  1. getting within obj implies looping
  2. identify objects: avoid element not being object typed and only checks for object typed
  3. going deeper: for nested objects, a recursive pattern is handy.
    ( careful to avoid infinite loop w/ recursive function execution )
  4. delete/remove obj if empty

Code snippet:

 const test = {
 a: "a", b: {},
 c: { c: {} },
 d: {
 d: { e: {} }
 },
 }
 function checkObjEmptiness(obj) {
 // increases readability
 // avoid "typeof" checking as "typeof [] === 'object' // returns true"
 
 let isObject = (x) => x && x instanceof Object, 
 isEmpty = (x) => x && !Object.keys(x).length;
 // 1. loops over obj to check each elements emptiness
 for (let k in obj) {
 // 2. check for object within object based on: isObject && !isEmpty
 // 3. if object and not empty --> re-apply processus
 if (isObject(obj[k]) && !isEmpty(obj[k])) checkObjEmptiness(obj[k]);
 // handles deletion on obj if empty [ or value if empty ]
 //if (isEmpty(obj[k]) || !obj[k]) delete obj[k]; // handles empty values
 // 4. deletes object if empty
 if (isEmpty(obj[k])) delete obj[k]; //handles empty object
 }
 return obj;
 }
 checkObjEmptiness( test )

answered Aug 16, 2020 at 15:48

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.