Check out our Angular Book Series.

How do I combine Objects in JavaScript? Use object.assign()!

Let's say we have a config object being passed into a method. A lot of the config values are optional, and we want to default them if they are left out before the method does it's magic. The structure is like this:


function conditionalConfig(config){
if(!config.option1){
config.option1 = defaultOption1Value;
}
if(!config.option2){
config.option2 = defaultOption2Value;
}
// etc.. etc.. etc..
// do other stuff
}

The code works great, but it is tedious to write all those conditionals. Is there a way to simplify it? Yes there is and I'm going to talk about two ways to do that. Today we'll cover object.assign().

Object Assign

The first way to simplify this code is to use object.assign(). Object.assign() will copy all the values from one object into another. First, create an object instance with all the default values:


function defaultConfigWithAssign(config){
defaultObject = {
option1 : 'DefaultValue1',
option2 : 'DefaultValue2',
option3 : 'DefaultValue3',
option4 : 'DefaultValue4',
}

Now use Object.assign() to combine that with your function argument:


Object.assign(defaultConfig,config)
// dump to console for testing purposes
console.log(config);
console.log(defaultConfig);
// do other stuff
// end function
}

You can test this like this:


customConfigObject = {
option1 : 'Value1',
option2 : 'Value2',
option3 : 'Value3',
}
defaultConfigWithAssign(customConfigObject);

Look at the console output and you'll see that the original config object is unchanged, but the default object contains all the new values:

The custom values from our config argument are retained and the unset default value--option4--is set with the new config.

You have to be careful when doing this to keep around a clean version of the default object since it is modified with this approach. I addressed that by creating the default config inside the function, as opposed to some permanent store.

Play with the code here.

Next week I'm going to talk about the Spread operator which can be used to accomplish the same thing.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.