I need to add an item to an object if the object exists, otherwise I need to create new object with the item.
I know the existence of Object.assign function, but I am not sure how to use it.
Right now this is what I tried:
var myvar = obj ? Object.assign(obj, { "myvar" : "myvalue" }) : { "myvar" : "myvalue" };
Is this the right and the cleaner way to do that?
copy/pasted from one of my owns projects
Personnaly, I always do that :
var forms = forms || {};
forms.state = forms.state || {};
first line : if 'forms' was previously undefined or null, it will create a new object. Otherwise, forms will be assigned to its previous value. (I use that a lot when I have applications with simple JS or Jquery only), it allows me to kind of namespace my application without caring about file loading order.
The second line checks if the object 'state' already exists. If it already exists, it assigns 'forms.state' to 'forms.state'. Otherwise, it creates a new object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With