Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

189
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda