JSON.stringify踩坑

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}"
posted @ 2023-01-05 15:37  SangFall  阅读(105)  评论(0)    收藏  举报