Skip to content

Instantly share code, notes, and snippets.

@kevinchisholm
Last active October 6, 2019 19:23
Show Gist options
  • Save kevinchisholm/e5f085c1342c945f9043194046a63ab6 to your computer and use it in GitHub Desktop.
Save kevinchisholm/e5f085c1342c945f9043194046a63ab6 to your computer and use it in GitHub Desktop.
Quick and Dirty Way to Copy a JavaScript Object
//--------- PART 1 -------------------
const objectA = {
foo: ['a', 'b', 'c']
};
const objectB = Object.assign({}, objectA);
console.dir(objectB); // {"foo":["a","b","c"]}
objectA.foo.push('d');
objectA.foo.push('e');
console.dir(objectB); {"foo":["a","b","c"]} //{"foo":["a","b","c","d","e"]}
//--------- PART 2 -------------------
function copyObject (objectToCopy) {
return JSON.parse(JSON.stringify(objectToCopy));
};
const objectA = {
foo: ['a', 'b', 'c']
};
const objectB = copyObject(objectA);
console.dir(objectB); // {"foo":["a","b","c"]}
objectA.foo.push('d');
objectA.foo.push('e');
console.dir(objectB); // {"foo":["a","b","c"]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment