0

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: {}
}
0

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.