JSON.parse(JSON.stringify(x)) Purpose?

While I was working on a project, I came across this snippet of code:

var params = JSON.parse(JSON.stringify(defaultParams));

Does this code actually do anything?

It’s a way of cloning an object, so that you get a complete copy that is unique but has the same properties as the cloned object.

var defaultParams = { a : 'b' };
var params = JSON.parse(JSON.stringify(defaultParams));

console.log( params.a ); // b
console.log( defaultParams.a ); // b
console.log( params === defaultParams ); // false

The above outputs false because even though both objects have the a property, with the value b, there are different objects that are independent of each other (they don’t refer to the same reference).

The JSON method will only work with basic properties – no functions or methods.

You can break the connection between two arrays.

For example:

const bulkAssignTreeView = JSON.stringify(this.bulkAssignTreeViewData);
this.bulkAssignTreeViewData = JSON.parse(bulkAssignTreeView);


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Sending websocket ping/pong frame from browser

Similar Posts