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
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)
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