简体   繁体   English

使所有属性可枚举

[英]Make all properties enumerable

Say I have an Error object: new Error('foo')假设我有一个错误 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:您可以使用 spread 复制可枚举属性,然后手动添加stackmessage属性:

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 :对于更通用的解决方案,要创建具有可枚举属性的新 object,请使用Object.getOwnPropertyNames

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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