Object.assign({},objToClone)
ES6 allows easy shallow cloning objects with Object.assign which also allows for MULTIPLE combining
Object.assing({}, null, a,b,c) // object with props from a, b, and c
Should be put in a more robust version?
const shallowClone = (...objs) => Object.assign({}, ...objs)
Or remove it since now it's part of spec?
Well shallowClone implies it's just cloning one object, not assigning the properties of several into one. It's also a utility because it's shorter than Object.assign. There are other utilities like head of list that are like that.
how is shallowClone shorter than Object.assign?
ugh tried ot clear out a comment, ignore the toggle
Object.assign() and { ...obj } are both ES6 and both work as far as shallow cloning goes (different techniques). Unless you can provide an argument why one of them is better than the other (performance or semantics or side-effects), we will sit here all day debating which one to use. So we better come up with an argument which one is the de-facto implementation and then update the snippet.
I want to keep the shallow clone snippet at all costs, as it is something that many new developers struggle with, so even if it is dead simple, it is helpful.
I believe that { ...obj } is actually not in the standard yet, it's a stage-3 proposal. I think it will be ES2018.
@atomiks in that case send a PR with the change to use Object.assign() (after you've double-checked) and I'll merge it.
Well it's implemented in browsers and babel, so I think it's fine to use. But it's not from ES6.
(I don't have the time to check either one right now, maybe later)
The object spreads operator is slightly faster than Object.assign(), but it's not as well-supported. I'll close the issue and switch the current snippet to use Object.assign() for better support.
PS after thoughts(do not reopen)
You might want to create a hanging issue about changing it to the spread operator once fully supported then. I like Object.assign a little better because you can make two functions with the exact same footprint:
const shallowClone = merge = (...args) => Object.assign({},...args)
but that's hardly a reason to keep one over the other unless we want to show that you can also define two things to point at the same reference by chaining, but then shallowClone becomes overloaded
@skatcat31 careful, that makes merge a global variable
(() => {
const shallowClone = merge = (...args) => Object.assign({},...args);
})();
console.log(merge); // no error
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for any follow-up tasks.