Preserving undefined that JSON.stringify otherwise removes

前端 未结 7 1689
长情又很酷
长情又很酷 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-23 19:04

    You can pass a replacer function to JSON.stringify to automatically convert undefined values to null values, like this:

    var string = JSON.stringify(
      obj,
      function(k, v) { return v === undefined ? null : v; }
    );
    

    This works for undefined values inside arrays as well, as JSON.stringify already converts those to null.

提交回复
热议问题