← Back to all TILs

Spread Merging Objects Includes Nil Values

javascript Written August 14, 2022

A handy way to merge two objects together with ES6 JavaScript syntax is to use the spread operator.

const combinedObj = { ...obj1, ...obj2 };

All the key-value pairs from each object are combined into a new object. For any overlapping keys, the last occurrence's value will take precedence.

That bit about precedence is true for nil values – null and undefined – as well.

const obj1 = { taco: 'bell', hello: 'world', list: [1,2,3] }
const obj2 = { burrito: 'house', hello: null, list: undefined }

const combinedObj = { ...obj1, ...obj2 }
//=> { taco: 'bell', hello: null, list: undefined, burrito: 'house' }

Notice that even though there are "actual" values for the hello and list keys in obj1, they are overridden by the null and undefined values in obj2.

Other posts like this