There are a couple ways to clone. If all you need is a shallow clone (your object only contains one level of primitives), Object.assign()
is a handy way to do it:
const fromObj = { a: 1, b: 2, c: 3 };
const toObj = Object.assign({}, fromObj);
The Object.assign()
function basically says "Assign all properties from the other objects to the first one". By making the first one an empty object, it is effectively a clone.
If you need a more controlled copy, you can use Object.keys()
so you don't have manually have an array that lists properties:
// concise example using reduce and assign
const cloneA = obj => Object.keys(obj).reduce((result, key) => Object.assign(result, { [key]: obj[key] }), {});
// using a for-loop
const cloneB = obj => {
const result = {};
const keys = Object.keys(obj);
for(let i in keys) {
result[keys[i]] = obj[keys[i]];
}
return result;
}
const fromObj = { a: 1, b: 2, c: 3 };
console.log(cloneA(fromObj));
console.log(cloneB(fromObj));
If you need to deal with anything other then primitives, you want a deep clone function. There are lots of libraries with them out there, so I won't re-implement one here, but basically it's a recursive version of one of my clone functions that checks if it's a primitive or not before the copy.