Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

190
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda