Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add item to object if the object exists or create new object if it does not exists

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?

like image 855
Giacomo M Avatar asked Nov 30 '25 07:11

Giacomo M


1 Answers

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.

like image 155
Deblaton Jean-Philippe Avatar answered Dec 02 '25 21:12

Deblaton Jean-Philippe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!