Javascript - check if the key exists - if not create it, all on one line

I am looking for a one-line way to check for a key and if it does not create one.

var myObject = {}; //Anyway to do the following in a simpler fashion? if (!('myKey' in myObject)) { myObject['myKey'] = {}; } 
+7
javascript
source share
6 answers

Short circuit rating:

 !('myKey' in myObject) && (myObject.myKey = {}) 
+8
source share
 myObject['myKey'] = myObject['myKey'] || {}; 
+4
source share

You can use hasOwnProperty or typeof to check for outputs or undefine ...

+2
source share

Comment: I usually prefer @Nindaff and @MoustafaS answers depending on the circumstances.

For completeness, you can create key / values ​​using Object.assign for any keys that were not there. This is most useful when you have default options / options that you want to use, but allow users to overwrite via arguments. It will look like this:

 var myObject = {}; myObject = Object.assign( { 'myKey':{} }, myObject ); 

Here is the same with a slightly larger output:

 var obj = {}; console.log( 'initialized:', obj); obj = Object.assign( {'foo':'one'}, obj ); console.log( 'foo did not exist:', obj ); obj = Object.assign( {'foo':'two'}, obj ); console.log( 'foo already exists:', obj ); delete obj.foo; obj = Object.assign( {'foo':'two'}, obj ); console.log( 'foo did not exist:', obj ); 

Note: Object.assign is not available in IE, but there is Polyfill

+2
source share

You can use Object.keys() , Object.hasOwnProperty()

 var key = {myKey:{}}, prop = Object.keys(key).pop(), myObject = {}; if (!myObject.hasOwnProperty(prop)) {myObject[prop] = key[prop]} console.log(myObject) 
+1
source share

There is a Proxy assigned internal type suitable for this task:

 const myObj = new Proxy({}, { get (target, key) { return target.hasOwnProperty(key) && target[key] || (target[key] = {}); } }); typeof myObj.foo === 'object' && (myObj.bar.quux = 'norf') && myObj.bar.quux === 'norf'; 
0
source share

All Articles