Replace null values to empty values in a JSON OBJECT

前端 未结 8 1683
無奈伤痛
無奈伤痛 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)
    
    0 讨论(0)
  • 2020-12-31 07:53

    You can replace null values to empty by below code in java-script

    var remove_empty = function ( target ) {
      Object.keys( target ).map( function ( key ) {
        if ( target[ key ] instanceof Object ) {
          if ( ! Object.keys( target[ key ] ).length && typeof target[ key ].getMonth !== 'function') {
            target[ key ] = "";
          }
          else {
            remove_empty( target[ key ] );
          }
        }
        else if ( target[ key ] === null ) {
           target[ key ] = "";
        }
      } );
      return target;
    };
    

    you can read more about Object.keys

    0 讨论(0)
提交回复
热议问题