My goal was to create a single-line function that produces a deep copy of a javascript object.
Requirements:
- Executable on a single line without the use of semicolons (exception: last character of the line)
- Nested objects should not be references to the originals
Function:
let copiedObjct = (copy = (obj) => (Object.keys(obj).reduce((v, d) => Object.assign(v, {[d]: (obj[d].constructor === Object) ? copy(obj[d]) : obj[d]}), {})))(obj);
Usage (expanded):
let obj = { /*...*/ }
let copiedObjct = (copy = (obj) => (
Object.keys(obj).reduce((v, d) => Object.assign(v, {
[d]: (obj[d].constructor === Object) ? copy(obj[d]) : obj[d]
}), {})
))(obj);
My questions are:
- Is this code efficient?
- Are there any reasons this shouldn't be used in the wild?
- Is there a way I can make it shorter?
JSON.parse(JSON.stringify(obj))
with some caveats may work for you. \$\endgroup\$Is there a way I can make it shorter?
: 163b -> 144b:let copiedObjct=(copy=(obj)=>(Object.keys(obj).reduce((v,d)=>Object.assign(v,{[d]:(obj[d].constructor===Object)?copy(obj[d]):obj[d]}),{})))(obj)
\$\endgroup\$const copy = obj => typeof obj == 'object' ? Object.entries(obj).reduce((r, [k, v]) => (r[k] = copy(v), r), {}) : obj
, still somewhat readable... though Joseph really has the right answer here. \$\endgroup\$