I am trying to remove null/empty elements from JSON objects, similar to the functionality of the python webutil/util.py -> trim_nulls method. Is there something built in to Node that I can use, or is it a custom method.
Example:
var foo = {a: "val", b: null, c: { a: "child val", b: "sample", c: {}, d: 123 } };
Expected Result:
foo = {a: "val", c: { a: "child val", b: "sample", d: 123 } };
In order to ignore null fields at the class level, we use the @JsonInclude annotation with include. NON_NULL.
To remove JSON element, use the delete keyword in JavaScript.
Null valuesJSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.
To remove a null from an array, you should use lodash's filter function. It takes two arguments: collection : the object or array to iterate over. predicate : the function invoked per iteration.
I don't know why people were upvoting my original answer, it was wrong (guess they just looked too quick, like I did). Anyway, I'm not familiar with node, so I don't know if it includes something for this, but I think you'd need something like this to do it in straight JS:
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') {
delete target[ key ];
}
else {
remove_empty( target[ key ] );
}
}
else if ( target[ key ] === null ) {
delete target[ key ];
}
} );
return target;
};
remove_empty( foo );
I didn't try this with an array in foo
-- might need extra logic to handle that differently.
You can use like this :
Object.keys(foo).forEach(index => (!foo[index] && foo[index] !== undefined) && delete foo[index]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With