DEV Community

Discussion on: Copying Javascript Objects in an efficient way

Collapse
 
ganeshmani profile image
GaneshMani

By doing json serialization, you will lose any Javascript property that has no equivalent type in JSON, like Function or Infinity. Any property that’s assigned to undefined will be ignored by JSON.stringify, causing them to be missed on the cloned object.

Collapse
 
einperegrin profile image
Roman Sokolov

Yes, I agree with you. And I've noticed it in the comment below. But there are no functions or Infinity in your example, thus this way is the most efficient for objects like this.
For complicated objects, it's safer (safer, not faster) to use some custom realizations or even cloneDeep from lodash/cloneDeep (or just package 'lodash.cloneDeep'). But there are no reasons to pull the whole lodash library if you don't want to use all of its methods. It just inflates your bundle size.
So, let's come to a consensus: it’s good when you know your data and tools and select the tools suitable for the data and tasks :-)