Sunday, April 30, 2017

JavaScript: Copy Object

Assuming we/the user(s) use latest browser.


For instance, if we have this object:

And we want to clone it and make it editable without affecting the original object, so DO NOT DO THIS:

Because every time the original object changes, the "new_object_clone" variable will also change, and vice versa.

We need to construct new object and copy the keys / values into it.

Just like copying array. But, array has built-in function, that is the slice.


Here goes for cloning object...

#1 Manual


How to use it


#2 Using new feature, assign


Why the "assuming"?

Because olden browsers don't support, either the Object.keys new function, or the Object.assign, or the forEach looper.


jQuery?

Using jQuery, it's more "polyfill-ed", can accommodate olden browser too. Check out this answer on Stack Overflow

No comments:

Post a Comment

Tell me what you think...