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

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

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 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