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

144
Visualizações
How to save parent.child name with looping through a nested object in JavaScript? like {parent.child : "value"}

I have an object as an input with a structure like this:(basically a simple nested object)

const test ={
  id: "0000",
  parent1 : "foo",
  parent2: { child1: "data1",
             child2: "data2",
             child3: "data3" 
           },
  parent3: { child1: "data1",
             child2: "data2",
             child3:  "data3"
           } 
}

This test object has some empty values, and the purpose of the code is to loop through the object and find properties with values.

const update = {};
  for(const key in test){
    if(test[key] !== ""){
      update[key] = test[key];
      console.log(update);
    }
  };

The loop works just fine finding them. But when it finds a child, it saves it like this, as an example, {child: "data2"} and won't save the parent's name.

How is possible to modify this code and avoid too many if/else conditions, basically an optimized code, when having an object like this:

{
  id: "foo",
  parent1 : Null,
  parent2: { child1: Null,
             child2: "data2",
             child3: Null
           },
  parent3: { child1: Null,
             child2: Null,
             child3:  "data3"
           } 
}

A result like this:

{ id: "foo", parent2.child2: "data2", parent3.child3: "data3"]

or more likely something like this:

{ id: "foo", parent2:{child2: "data2"}, parent3:{child3: "data3"}}
about 4 years ago · Juan Pablo Isaza
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