简体   繁体   中英

Make all properties enumerable

Say I have an Error object: new Error('foo')

I want to serialize it, the problem is the stack/message properties are not enumerable.

So I want to do something like this:

const json = JSON.stringify(Object.assign({}, new Error('foo')));

but this copies the properties and they remain non-enumerable, which means they won't get serialized. So my question is - is there a way to copy the properities but make them all enumerable, something like so:

const v = {};

for(const [key, val] of Object.entries(new Error('foo')){
  Object.defineProperty(v, key, {
        value: val,
        enumerable: true
   })
}

is there some way to do that for just two properties?

You can copy the enumerable properties with spread and then manually add in the stack and message properties:

const err = new Error('foo');
const errorWithEnumerableStackAndMessage = { ...err, err.stack, err.message };

For a more general solution, to create a new object with enumerable properties, use Object.getOwnPropertyNames :

 const toEnumerable = (obj) => { return Object.fromEntries( Object.getOwnPropertyNames(obj).map(prop => [prop, obj[prop]]) ); }; console.log(toEnumerable(new Error('foo')));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM