Replace null values to empty values in a JSON OBJECT

前端 未结 8 1774
無奈伤痛
無奈伤痛 2020-12-31 06:54

Hi I\'ve got a JSON object provided by an ajax request.

Some of the values inside the json appears as null, but I want an empty String inst

8条回答
  •  不知归路
    2020-12-31 07:48

    For anyone still looking for a solution.

    Used this in my angular 2 app to remove all null values returned by my db query.

    Create an angular 2 function in the component

        replacer(i, val) {
         if ( val === null ) 
         { 
            return ""; // change null to empty string
         } else {
            return val; // return unchanged
         }
        }
    

    Or Javascript function

        function replacer(i, val) {
         if ( val === null ) 
         { 
            return ""; // change null to empty string
         } else {
            return val; // return unchanged
         }
        }
    

    Then use the function in JSON.stringify method

        JSON.stringify(result, this.replacer)
    

提交回复
热议问题