Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I have an object, x. I'd like to copy it as object y, such that changes to y do not modify x. I realized that copying objects derived from built-in JavaScript objects will result in extra, unwanted properties. This isn't a problem since I'm copying one of my own, literal-constructed objects.

How do I correctly clone a JavaScript object?

1 Answer

0 votes
by (106k points)

For correctly cloning a JavaScript object you can use the JSON.parse(JSON.stringify(object)) method,  below is the code for the same:-

const a = { string: 'string', number: 123, bool: false, nul: null, date: new Date(),} 

console.log(a); 

console.log(typeof a.date);

const clone = JSON.parse(JSON.stringify(a)); 

console.log(clone); 

console.log(typeof clone.date);

Related questions

0 votes
1 answer
asked Aug 12, 2019 in Web Technology by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...