JSON.parse(JSON.stringify(obj)) Removes Undefined. How to Keep them!

Clint Pitzak
1 min readJun 20, 2019

Cloning an Object in JavaScript is easy as JSON.parse(JSON.stringify(obj)) unless you have undefined object attributes. Here is the problem…

> var obj = { a: 2, b: null, c: undefined };
var result = JSON.parse(JSON.stringify(obj));
console.log(result);
{a: 2, b: null}

You might ask, we’ll isn’t the following true:

> obj.c
undefined
> result.c
undefined

So what’s the problem? We’ll the problem depends on how you check what’s inside your result object.

See the problem below:

> 'c' in obj
true
> 'c' in result
false
> obj.hasOwnProperty('c')
true
> result.hasOwnProperty('c')
false
> Object.keys(obj).length
3
> Object.keys(result).length
2

Fortunately the JSON.stringify method provides a second parameter that accepts a function to alters the behavior of the stringification process.

We make a function that will change undefined object attributes to null object attributes to fix this issue:

> var obj = { a: 2, b: null, c: undefined };
var replacer = function(key, value) {
return typeof value === 'undefined' ? null : value;
}
var result = JSON.parse(JSON.stringify(obj, replacer));
console.log(result);
{a: 2, b: null, c: null}

Now when we do the following we have the desired output:

> 'c' in obj
true
> 'c' in result
true
> obj.hasOwnProperty('c')
true
> result.hasOwnProperty('c')
true
> Object.keys(obj).length
3
> Object.keys(result).length
3

--

--