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!
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:
!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")Just replace inputKey and inputValue with the variable names for your input.
Hope this is what you're looking for!