javascript - 根据上下文以不同方式对对象进行字符串化

标签 javascript node.js json

我有一个带有 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/

相关文章:

json - 在 Ansible 中过滤 JSON 文档

javascript - onbeforeunload 根本不起作用

javascript - jQuery .index() 的奇怪之处

javascript - 如何创建一个等待 Javascript 事件的异步函数?

node.js - NodeJS CLD包外部依赖项

javascript - Json过滤数据并按顺序排序

python - 通过Hadoop Streaming运行Python MapReduce脚本时获取 “ValueError: No Json object could be decoded”

javascript - 每个 div 内必须至少选中一个复选框

javascript - 类型错误 : Class extends value undefined is not a constructor or null in react js

java - JHipster - 在 build.gradle 中放置附加模块/插件的位置