Replace null with empty when using JSON.stringify()

Let's assume that you have the following JavaScript object:

javascript
let dishes = ['Salad', , 'Steak', 'Ice cream']

Let's assume that you wanted to do a deep copy of it:

javascript
let deepCopy = JSON.parse(JSON.stringify(dishes))
// ['Salad', null, 'Steak', 'Ice cream']

The copy isn't accurate, because the empty position of the array is transformed into a null element by default. You can use a replacer in the JSON.parse() function to avoid it.

Example:

javascript
let replacer = (key, value) => value === null ? undefined : value

let deepCopy = JSON.parse(JSON.stringify(dishes), replacer)
// ['Salad', empty, 'Steak', 'Ice cream']

The difference between an empty position is that it is undefined, whereas a null position isn't.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.