From 6ced078936f9c30fdcac057610c9db16058bc800 Mon Sep 17 00:00:00 2001 From: atomiks Date: Fri, 15 Dec 2017 08:17:21 +1100 Subject: [PATCH] Create shallow-clone-object.md We need a deep clone too but that's a different animal. `JSON.parse(JSON.stringify(obj))` is not very good because it strips functions, etc. --- snippets/shallow-clone-object.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 snippets/shallow-clone-object.md diff --git a/snippets/shallow-clone-object.md b/snippets/shallow-clone-object.md new file mode 100644 index 000000000..7993e8243 --- /dev/null +++ b/snippets/shallow-clone-object.md @@ -0,0 +1,12 @@ +### Shallow clone object + +Use the object spread operator to spread the properties of the target object into the clone. + +```js +const shallowClone = obj => ({ ...obj }); +/* +const a = { x: true, y: 1 }; +const b = shallowClone(a); +a === b -> false +*/ +```