Created
October 7, 2015 22:13
-
-
Save brittanmcg/f26134cb49d6cf73735c to your computer and use it in GitHub Desktop.
object with some values as objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var obj = { | |
name: "Simon", | |
age: "20", | |
clothing: { | |
style: "simple", | |
isDouche: false | |
} | |
} |
@elreimundo Thanks for clearing up those issues! I totally forgot to change thing
to deepCopy
when I renamed the function haha. @konamax123 Copying in JS is rough because there are a lot of subtleties to consider when duplicating the memory allocated to objects and their contents. If you want a solution free of headaches (for the most part) consider Immutable data structures. They use structural sharing so creating "copies" isn't really that expensive. A good library is Facebooks ImmutableJS
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just to clean up @arcin 's suggestion, which is good but which has three errors (assigning
newObj
without checking its type first, iterating over the prototype without checkinghasOwnProperty
, and calling an incorrect methodthing
instead ofdeepCopy
)results in the console:
note that all of these naive implementations (including mine) will "fail" if you have any circular references, e.g.
since you will kick off an infinite loop. These deep copies work only for acyclic graphs or trees.
result in console: