Replace null values to empty values in a JSON OBJECT

前端 未结 8 1772
無奈伤痛
無奈伤痛 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: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

提交回复
热议问题