mkirouac
mkirouac

Reputation: 123

Removing element with NULLs from a JSON object in JQuery/Javascript

I saw some questions on StackOverflow covering the subject but I was not able to make it work with any of the solutions I found. It seems to be a common problem but I suspect I might not be building the JSON object correctly.

I am getting some fields from a form to get real-time reasons from a query in the database. But if the fields are empty, I still get them in the JSON as field : null.

This is the Jquery code :

    $(document).ready(function() { 
   $('select').change(function() {       
        //var formData = JSON.stringify($("#cstates").serializeArray());

       var states = { states : $("#cstates").val(), zips : $("#czips").val()};

        //var data = JSON.stringify(states).replaceAll(".*\": null(,)?\\r\\n", "");
        //{"states":null,"zips":["91941"]}
        //str.replaceAll(".*\": null(,)?\\r\\n", "");

        alert(JSON.stringify(states));
        $.ajax({
          type: "POST",
          url: "http://localhost:8080/api/campaign/stats",
          data: JSON.stringify(states),
          cache: false,
          success: function(data){
             $("#resultarea").text(data);
          },
          dataType: "json",
          contentType : "application/json"
        });

   }); 
});

I get that kind of output : {"states":null,"zips":["91941"]} but what I want in this situation where the state dropdown is empty is {"zips":["91941"]}. Basically, I want in the JSON only values that have a filled field in the HTML form.

Upvotes: 1

Views: 445

Answers (1)

Ahmed Elbendary
Ahmed Elbendary

Reputation: 379

// this function to remove null or empty value

 const removeEmptyOrNull = (obj) => {
  Object.keys(obj).forEach(k =>
    (obj[k] && typeof obj[k] === 'object') && removeEmptyOrNull(obj[k]) ||
    (!obj[k] && obj[k] !== undefined) && delete obj[k]
  );
  return obj;
};

$(document).ready(function() {

$('select').change(function() {
//var formData = JSON.stringify($("#cstates").serializeArray());

   var states = { states : $("#cstates").val(), zips : $("#czips").val()};

    //var data = JSON.stringify(states).replaceAll(".*\": null(,)?\\r\\n", "");
    //{"states":null,"zips":["91941"]}
    //str.replaceAll(".*\": null(,)?\\r\\n", "");

    alert(JSON.stringify(states));
    $.ajax({
      type: "POST",
      url: "http://localhost:8080/api/campaign/stats",
      data: JSON.stringify( removeEmptyOrNull(states) ),
      cache: false,
      success: function(data){
         $("#resultarea").text(data);
      },
      dataType: "json",
      contentType : "application/json"
    });

}); });

Upvotes: 1

Related Questions