Skip to content

Instantly share code, notes, and snippets.

@paduc
Last active December 3, 2020 22:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paduc/a3e95630ce8cfde35316 to your computer and use it in GitHub Desktop.
Save paduc/a3e95630ce8cfde35316 to your computer and use it in GitHub Desktop.
Immutable merge for multiple objects (using lodash)
var _ = require('lodash');
function immutableMerge(){
if(arguments.length === 0) return {};
if(arguments.length === 1) return arguments[0];
if(arguments.length === 2) {
return _.merge(_.cloneDeep(arguments[0]), arguments[1]);
}
else{
return immutableMerge(_.first(arguments), immutableMerge(_.rest(arguments)));
}
};
@paduc
Copy link
Author

paduc commented Feb 13, 2015

Was looking for a way to join multiple style objects in React. It ended up looking like this.

   // jsx
   <div style={immutableMerge(styleA, styleB)}>Hello, world.</div>

@agarb7
Copy link

agarb7 commented Jun 4, 2018

I use this

_.merge({}, obj1, obj2, obj3)

@ngothanhtai
Copy link

Thanks @agarb7. I like your approach.

@derek-adair
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment