Googling for "javascript clone object" brings some really weird results, some of them are hopelessly outdated and some are just too complex, isn't it as easy as just:
let clone = {...original};
Is there anything wrong with this?
Googling for "javascript clone object" brings some really weird results, some of them are hopelessly outdated and some are just too complex, isn't it as easy as just:
let clone = {...original};
Is there anything wrong with this?
if you don't want to use json.parse(json.stringify(object)) you could create recursively key-value copies:
But the best way is to create a class that can return a clone of it self
Use Object.assign.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
However, this won't make a deep clone. There is no native way of deep cloning as of yet.
EDIT: As @Mike 'Pomax' Kamermans mentioned in the comments, you can deep clone simple objects (ie. no prototypes, functions or circular references) using
JSON.parse(JSON.stringify(input))
But Object.assign() not create a deep clone
To fix that, we should use the cloning loop that examines each value of user[key] and, if it’s an object, then replicate its structure as well. That is called a “deep cloning”.
There’s a standard algorithm for deep cloning that handles the case above and more complex cases, called the Structured cloning algorithm. In order not to reinvent the wheel, we can use a working implementation of it from the JavaScript library lodash the method is called _.cloneDeep(obj).
Totally acceptable, even moreso now that object spread is stage 3. People over complicate things.
const clone = {...original}
to cloneconst newobj = {...original, prop: newOne}
to immutably add another prop to original and store as a new object.