Skip to content
JSON학습 기록

Deep copying an object with JSON.stringify and JSON.parse

1 min readLearningMoved from my Tistory blogRead the Korean original

First, create a user object.

js
let user = {
    name: "sungjun",
    age: 50,
    size: {
        height: 200,
        weight: 70,
    }
};

Next, create a deepCopy object and convert the user object to a string with JSON.stringify(). Then convert the user string back into an object with JSON.parse(). (I think it's a really easy method.)

js
let deepCopy = JSON.parse(JSON.stringify(user));

Next, change deepCopy.size.height to 250 and look at the result. You can see that the value changes separately from the user object.

js
deepCopy.size.height = 250;
text
{ name: 'sungjun', age: 50, size: { height: 250, weight: 70 } }
{ name: 'sungjun', age: 50, size: { height: 200, weight: 70 } }
  • #deep copy
  • #JSON
  • #deep clone
  • #Zerobase
  • #frontend school

More in Learning