第二个参数(数组)
是的,stringify 函数也可以有第二个参数。它是要在控制台中打印的对象的键数组。看起来很简单?让我们更深入一点。我们有一个对象 product 并且我们想知道 product 的 name 属性值。当我们将其打印出来:
// product是一个对象
console.log(JSON.stringify(product));
它会输出下面的结果。
{"id":"0001","type":"donut","name":"Cake","ppu":0.55,
"batters":{"batter":[{"id":"1001","type":"Regular"},
{"id":"1002","type":"Chocolate"},{"id":"1003","type":"Blueberry"},
{"id":"1004","type":"Devil’s Food"}]},"topping":[{"id":"5001","type":"None"},
{"id":"5002","type":"Glazed"},{"id":"5005","type":"Sugar"}
,{"id":"5007","type":"Powdered Sugar"},{"id":"5006","type":"Chocolate with Sprinkles"},{"id":"5003","type":"Chocolate"},{"id":"5004","type":"Maple"}]}
在日志中很难找到 name 键,因为控制台上显示了很多没用的信息。当对象变大时,查找属性的难度增加。stringify 函数的第二个参数这时就有用了。让我们重写代码并查看结果
console.log(JSON.stringify(product,['name' ]);
// 结果
{"name" : "Cake"}
第二个参数(函数)
我们还可以传入函数作为第二个参数。它根据函数中写入的逻辑来计算每个键值对。如果返回 undefined,则不会打印键值对。请参考示例以获得更好的理解
const user = {
"name" : "Prateek Singh",
"age" : 26
}
// 结果
{ "age" : 26 }
只有 age 被打印出来,因为函数判断 typeOf 为 String 的值返回 undefined。
第三个参数为数字
如果第三个参数是 string,那么将使用它来代替上面显示的空格字符。
JSON.stringify(user, null,'**');
//{
//**"name": "Prateek Singh",
//**"age": 26,
//**"country": "India"
//}
// 这里 * 取代了空格字符
toJSON 方法
我们有一个叫 toJSON 的方法,它可以作为任意对象的属性。JSON.stringify 返回这个函数的结果并对其进行序列化,而不是将整个对象转换为字符串。参考下面的例子。
const user = {
firstName : "Prateek",
lastName : "Singh",
age : 26,
toJSON() {
return {
fullName: `${this.firstName} + ${this.lastName}`
};
}
}
console.log(JSON.stringify(user));
// 结果
// "{ "fullName" : "Prateek Singh"}"