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

160
Visualizações
Remove property from javascript object

I'm having troubles deleting properties with no keys in its value.

obj = {person: {id: 1, name: 'isaac'}, 
       location: {id: 1, name: 'UT'}, 
       status: {id: 1, name: 'Active'}, 
       empty: {}
}
for (key in obj) {
    if (Object.keys(obj.key).length == 0) {
        delete obj.key
    }
}

Running this code in chrome console I get the error:

Uncaught TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at <anonymous>:2:16
(anonymous) @   VM13940:2

I know this comes from Object.keys receiving null or undefined.

I don't understand how unless there is something going on with the object Prototype that I'm not seeing.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Oops! You meant:

for (key in obj) {
    if (Object.keys(obj[key]).length == 0) {
        delete obj[key]
    }
}

obj.key is actually obj["key"] But you meant to access the property of obj whose name is stored in the key variable, which is expressed as obj[key].

about 4 years ago · Juan Pablo Isaza Relatório

0

You are super close, but you are looking for 'key' as a property in your object. If you need to use a variable to reference a key of a object you have to use [].

The following code will do what you are looking to achieve:

for (key in obj) {
    if (Object.keys(obj[key]).length == 0) {
        delete obj[key]
    }
}
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