if the source's prototype is some descendant of Object, then we are going to be missing the additional members from that prototype which we skipped using the hasOwnProperty filter
The date string for d1 will be 5 seconds behind that of d2. A way to make one Date the same as another is by calling the setTime method, but that is specific to the Date class. we don't think there is a bullet-proof general solution to this problem, though we would be happy to be wrong!
This can be accomplished with code like the following:
The above function will work adequately for the 6 simple types we mentioned, as long as the data in the objects and arrays form a tree structure. That is, there isn't more than one reference to the same data in the object. For example:
Solution 2:
With jQuery, we can shallow copy with
subsequent changes to the copiedObject will not affect the origina lObject, and vice versa.
Or to make a deep copy:
Solution 3:
If we do not use functions within your object, a very simple one liner can be the following:
This works for all kind of objects containing objects, arrays, strings, booleans and numbers.
See also this article about the structured clone algorithm of browsers which is used when posting messages to and from a worker. It also contains a function for deep cloning.
Solution 4:
In ECMAScript 6 there is Object.assign method, which copies values of all enumerable own properties from one object to another. For example:
But be aware that nested objects are still copied as reference.
Solution 5:
There are many answers, but none that mentions Object.create from ECMAScript 5, which admittedly does not give we an exact copy, but sets the source as the prototype of the new object.
Thus, this is not an exact answer to the question, but it is a one-line solution and thus elegant. And it works best for 2 cases:
Where such inheritance is useful (duh!)
Where the source object won't be modified, thus making the relation between the 2 objects a non issue.
Example:
Why do we consider this solution to be superior? It's native, thus no looping, no recursion. However, older browsers will need a polyfill.