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

134
Visualizações
how to return an object under conditions

I’ve just started using objects (Im learning javascript). So I have an object and this is what should happen: The user insert some data; if there’s already this data in my object, I would return the object as it is; but if keys and values are new, I have to return an object that contains my previous data and the new.

For example let User = { “name”:”Ed”, “age”: 3 } The user wants to add a new property to User, or maybe he just forgot that there’s already a name. So I want to give him back his object, but with the new info only if they are really new. I found here that sometimes you can use Map on the object and I tried but it doesn’t work... I’m really lost and don’t know where to ask!

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

0

If I'm understanding correctly, if the user inputs a key-value pair but the key already exists then you want to return the object as-is, and if they input something with a new key you want to add it to the object. Here's how you can do that:

if (!User.hasOwnProperty(inputKey)) {
    User[inputKey] = inputValue;
}
return User;

How this works:

  • The expression !User.hasOwnProperty(inputKey) evaluates to True if the input key does not already exist in the object, or False if it does (this would be flipped without the !, meaning "not")
  • If the key does not already exist in the object, we add the key-value pair to the object
  • Then we return the object. If the key already existed, then the object was not modified. If the key didn't exist yet, we added it to the object.

Just replace inputKey and inputValue with the variable names for your input.

Hope this is what you're looking for!

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