'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?
Solution 1:[1]
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.
Solution 2:[2]
Try
(obj||{})["myvar"] = "myvalue"
obj = { test: 'ok' };
var myvar = (obj||{})["myvar"] = "myvalue";
console.log(myvar);
console.log(obj);
Solution 3:[3]
Can use the object spread operator.
var myvar = { ...obj, "myvar": "myvalue"}
Solution 4:[4]
Test if the object is defined.
let obj = null;
if (typeof obj === "undefined") obj = {};
let updatedObj = Object.assign({},obj, {"myVar": "my value"});
console.log(updatedObj);
// or in one line
let obj2 = null;
let updatedObj2 = (typeof obj2 === "undefined")? {"myVar": "my value"} : Object.assign({},obj2, {"myVar": "my value"});
console.log(updatedObj2);
Edit: In case obj
is null
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Kamil Kiełczewski |
Solution 3 | Andy Jenkins |
Solution 4 |