Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

188
Views
How to remove empty objects from object by comparing with another object

I want to remove all empty objects from another object by comparing it with another. Example of this would be:

We have default object like:

defaultObj = {
  a: {},
  b: {},
  c: {
    d: {}
  }
};

And target object like this:

targetObj = {
  a: { x: {} },
  b: {},
  c: {
    d: {},
    e: {}
  },
  f: {}
};

Now, I need to perform operation on targetObj by comparing it with defaultObj, and remove all objects that remain empty, but leave every object in targetObj that weren't originally in default. Result of operation should look like this:

result = {
  a: { x: {} },
  c: {
    e: {}
  },
  f: {}
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Here is a solution that you can use which recursively iterates an object and removes the empty properties as defined in your use case. Make sure to create a deep copy of the object first (as shown in the example) so that the original does not get manipulated:

const defaultObj = {
  a: {},
  b: {},
  c: {
    d: {}
  }
};

const targetObj = {
  a: { x: {} },
  b: {},
  c: {
    d: {},
    e: {}
  },
  f: {}
};

// traverse the object
function removeEmptyObjectProperties(targetObject, defaultObject) {
  Object.keys(targetObject).forEach((key) => {
    if (defaultObject.hasOwnProperty(key)) {
      // checks if it is a json object and has no keys (is empty)
      if (targetObject.constructor === ({}).constructor && Object.keys(targetObject[key]).length === 0) {
        delete targetObject[key];
      } else {
        // iterate deeper
        removeEmptyObjectProperties(targetObject[key], defaultObject[key]);
      }
    }
  })
}

// deep copy to remove the reference
const targetObjDeepCopy = JSON.parse(JSON.stringify(targetObj));
// execute
removeEmptyObjectProperties(targetObjDeepCopy, defaultObj);
// result
console.log(targetObjDeepCopy)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!