Preserving undefined that JSON.stringify otherwise removes

前端 未结 7 1676
长情又很酷
长情又很酷 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:25
    function stringifyWithUndefined(obj, space) {
      const str = JSON.stringify(obj, (key, value) => value === undefined ? '__undefined__' : value, space);
      return str.replace(/"__undefined__"/g, 'undefined');
    }
    

    Example:

    const obj = {
      name: 'boda',
      email: undefined,
      country: 'africa'
    };
    console.log(stringifyWithUndefined(obj, 2));
    

    Result:

    {
      "name": "boda",
      "email": undefined,
      "country": "africa"
    }
    
    0 讨论(0)
提交回复
热议问题