Preserving undefined that JSON.stringify otherwise removes

前端 未结 7 1688
长情又很酷
长情又很酷 2020-12-23 18:33

How do I preserve undefined values when doing JSON.stringify(hash)?

Here\'s an example:

var hash = {
  \"name\" : \"boda\",
  \"email\" : undefined,
         


        
7条回答
  •  误落风尘
    2020-12-23 19:19

    You can preserve the key by converting to null since a valid JSON does not allow undefined;

    Simple one liner:

    JSON.stringify(obj, (k, v) => v === undefined ? null : v)
    

提交回复
热议问题