当前位置:网站首页>JSON. Function of the stringify() optional parameter

JSON. Function of the stringify() optional parameter

2022-06-23 03:12:00 It workers

JSON.stringify Is a tool function we often use , The second optional parameter actually has some tricks , This article explains two common ways to use optional parameters .

Array

Use JSON.stringify() The second optional parameter of , Extract a specific field from an array by passing it in .

The implementation code is as follows :

var person = {"name":"Jim Cowart","location":{"city":{"name":"Chattanooga","population":167674}
,"state":{"name":"Tennessee","abbreviation":"TN","population":6403000}},"company":"appendTo"};

JSON.stringify(person, ["name", "company"], 4);
// ~> "{
//      "name": "Jim Cowart",
//      "company": "appendTo"
// }"

function

In addition, this parameter can also be a function , Used to operate on data before it is returned . If you want to Set Stringing , It will be very convenient , for example :

const dude = {
  name: "Pawel",
  friends: new Set(["Dan", "Pedro", "Mr Gregory"])
};

const dudeStringified = JSON.stringify(dude, (key, value) =>
  value instanceof Set ? [...value] : value
);

console.log(dudeStringified);
// ~> {"name":"Pawel","friends":["Dan","Pedro","Mr Gregory"]}
原网站

版权声明
本文为[It workers]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/01/202201211648539417.html

猜你喜欢