user11810894
user11810894

Reputation:

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?

Upvotes: 3

Views: 851

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371089

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')));

Upvotes: 2

Related Questions