Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 218
Mingwei Samuel Avatar asked Jul 14 '14 19:07

Mingwei Samuel


People also ask

What does JSON parse JSON Stringify do?

JSON. parse() takes a JSON string and transforms it into a JavaScript object. Trailing commas are not valid in JSON, so JSON. parse() throws an error if the string passed to it has trailing commas.

What is JSON parse?

The JSON. parse() method parses a string and returns a JavaScript object. The string has to be written in JSON format. The JSON. parse() method can optionally transform the result with a function.

Is JSON Stringify and JSON parse safe?

stringify()) is a bad practice to clone an object in JavaScript. Cloning of objects often become a problem to JS programmers.


2 Answers

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.

like image 140
MrCode Avatar answered Oct 16 '22 13:10

MrCode


You can break the connection between two arrays.

For example:

const bulkAssignTreeView = JSON.stringify(this.bulkAssignTreeViewData);
this.bulkAssignTreeViewData = JSON.parse(bulkAssignTreeView);
like image 21
bazobehram Avatar answered Oct 16 '22 14:10

bazobehram