首页 > 其他分享 >JSON.stringify踩坑

JSON.stringify踩坑

时间:2023-01-05 15:45:24浏览次数:45  
标签:stringify const phone JSON Stanko user

JSON.stringify将忽略所有未定义的对象属性。
const user = { name: 'Stanko', phone: undefined };
user.phone; // -> undefined

const stringifiedUser = JSON.stringify(user); // -> "{\"name\":\"Stanko\"}"

const parsedUser = JSON.parse(stringifiedUser) // -> { name: "Stanko" }

// At the end it behaves the same
parsedUser.phone; // -> undefined
解决办法:利用JSON.stringify参数replacer
const user = { name: 'Stanko', phone: undefined };

const replacer = (key, value) =>
  typeof value === 'undefined' ? null : value;

const stringified = JSON.stringify(user, replacer); // -> "{\"name\":\"Stanko\",\"phone\":null}"

标签:stringify,const,phone,JSON,Stanko,user
From: https://www.cnblogs.com/sangfall/p/17027761.html

相关文章