我有一个带有 toJSON 方法的对象:
const v = {
foo: 'zoom1',
bar: 'zoom2',
toJSON(){
return {foo: this.foo}
}
}
当我调用 JSON.stringify(v)
时,我会得到 {foo:'zoom1'}
- 我的问题是 - 有没有办法根据谁调用 JSON.stringify() 来对其进行不同的字符串化,例如,如果我想要的话:
{bar: 'zoom2'}
相反?也许有一个很好的设计模式,不知道。
最佳答案
实际上,您可以使用替换器 parameter stringify的功能:
A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string.
示例:
const v = {
foo: 'zoom1',
bar: 'zoom2'
};
JSON.stringify(v, ['foo']);
// Outputs "{"foo":"zoom1"}
JSON.stringify(v, ['bar']);
// Outputs "{"bar":"zoom2"}
JSON.stringify(v, ['foo', 'bar']);
// Outputs "{"foo":"zoom1", "bar":"zoom2"}
关于javascript - 根据上下文以不同方式对对象进行字符串化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53678386/