Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a pure function to merge objects

Let's say I have the variables 'state' and 'newState'. I would like to create a pure function that returns 'state' updated with the properties (and sub properties) of 'newState'. Here is an example:

const state = {id:1, name:'aName', description: 'aDescription'};

const newState = {id:1, name:'newName', subItems: {id:3, type:'whatever'}};

The function would return:

{id:1, name:'newName', subItems: {id:3, type:'whatever'}}

I could use rest parameters but I don't know how to append as opposed to override. I can't just loop through the properties because I want the function to be pure (redux reducer).

Anyone have any ideas?

like image 593
Eitan Avatar asked Mar 27 '26 17:03

Eitan


1 Answers

You can use the spread syntax:

The Rest/Spread Properties for ECMAScript proposal (stage 4) adds spread properties to object literals. It copies own enumerable properties from a provided object onto a new object.

... or Object.assign with the 1st argument being an empty object:

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

const state = {id:1, name:'aName', description: 'aDescription'};
const newState = {id:1, name:'newName', subItems: {id:3, type:'whatever'}};

// Example with spread syntax:
const result1 = { ...state, ...newState };

// Example with Object.assign:
// @NOTE: Providing an empty `{}` as the 1st argument,
// ensures you don't mutate `state`.
const result2 = Object.assign({}, state, newState);

console.log(result1);
console.log(result2);

Side notes:

  • Expanding on @user633183's comment, both ways produce a shallow merge. They only go 1-level deep. If you're looking to do a deep merge, I suggest you check out this answer.

  • At the time of writing this, Object.assign has better cross-browser support than spread syntax on object literals, as you can see here. While this shouldn't be a problem if you correctly use Babel or any other transpiler, it is worth mentioning.

  • We don't usually refer to functions as immutable (actually they can be since they are values themselves but that's probably not what you mean in the context of your question). Values can be immutable, functions can be pure; meaning they don't cause side-effects such as mutating their arguments.

like image 187
nicholaswmin Avatar answered Mar 30 '26 09:03

nicholaswmin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!