Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!