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
BotNet
source share