Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - Remove null elements from JSON object

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 } };
like image 766
Steve Davis Avatar asked Aug 08 '12 23:08

Steve Davis


People also ask

How do I ignore null values in JSON object?

In order to ignore null fields at the class level, we use the @JsonInclude annotation with include. NON_NULL.

How do you remove an element from a JSON object?

To remove JSON element, use the delete keyword in JavaScript.

Can JSON take null values?

Null valuesJSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.

How do you remove null values from an array?

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.


2 Answers

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.

like image 142
JMM Avatar answered Oct 20 '22 01:10

JMM


You can use like this :

Object.keys(foo).forEach(index => (!foo[index] && foo[index] !== undefined) && delete foo[index]);
like image 40
Durmuş Avatar answered Oct 19 '22 23:10

Durmuş