I have this test script:
const n = new Error('foo');
n.bar = 'bar';
console.log(n); // doesn't show {stack: "", message:"" }
const x = Object.assign({}, n)
console.log(x); //{ bar: 'bar' }
console.log(x instanceof Error); // false
what I would like to do is this:
console.log(Object.assign({}, new Error('foo'))) // {message:"foo", stack:"foo..."}
is there a well-defined way to accomplish this? I assume Error has some overrides to make properties non-enumerable and also some override to dictate how it’s printed to console.
Note that if this was just for Error, I would just deconstruct it manually myself:
const v = {...e, message: e.message, stack: e.stack,}
but I would like to do same thing for other objects besides Error.
2
Answers
I guess it's as simple as this:
there is also this which may copy non-enumerable properties whereas the above doesn't?
if this is not sufficient, please add a comment.
Just copy own property descriptors. To make an identical copy use
structuredClone()
.