Quirk - JSON.stringify removes empty properties

Thursday, January 19th 2023

Problem

I noticed that when I was upserting docs in mongodb the fields where not getting reset because the value coming in was undefined instead of null.

Solution

Pass a custom replacer function to to JSON.stringify() so when a value is undefined, we use null instead.

const user = { name: 'Quirky', phone: undefined }; const replacer = (key, value) => (typeof value === 'undefined' ? null : value); const stringified = JSON.stringify(user, replacer); // -> "{\"name\":\"Quirky\",\"phone\":null}"