Last Updated: December 26, 2018
·
15.21K
· sschepis

Deep clone a javascript object without underscore or lodash

It's ridiculously simple:

var clone = JSON.parse(JSON.stringify(obj)); 

The only time this won't work is with objects with circular dependencies, which make JSON.stringify throw an error. Still, this is often a great solution in projects that require a deep clone but don't warrant packaging an entire library like lodash or underscore to do it.

3 Responses
Add your response

You made my day ;)

over 1 year ago ·

That's great! haha

over 1 year ago ·

This is a clever solution, however it doesn't copy keys with assigned functions as their values.

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside