skip to Main Content

I have below JSON. how to remove the values which contain blank value or null value using Javascript?

dataJSON==
    {
      "Cli Info:Sub_Ind":""
      "Cli Info:Sub_Mat":"",
      "Cli Info:Sub_Ewwu":"",
      "Cli Info:Sub_kjlo":"",
      "Cli Info:Sub_uti":"",
      "S Funds:S_C_origin":"Afghanistan;Albania",
      "S We:Count_we":"Antigua & Barbuda;American Samoa;Austria",
      "Add Juri:Jurid_Coun":"Andorra;Angola"
     }

i tried the approach but not working.


 function clean(obj) {
  for (var propName in obj) {
    if (obj[propName] === null || obj[propName] === undefined) {
      delete obj[propName];
    }
  }
  return obj
}

I am expecting to remove all the null,blank and undefined values from the JSON

3

Answers


  1. you can use replacer in the JSON.stringify

    here you can write your own custom replacer function

    
    const replacer = (key,val) => val==null || val==='' ? null : val;
    
    const sanitisedJSON = (arg) => JSON.parse(JSON.stringify(arg,replacer));
    
    
    Login or Signup to reply.
  2. This removes null and undefined values with a for in loop (PURE Javascript):

    dataJSON==
        {
          "Cli Info:Sub_Ind":""
          "Cli Info:Sub_Mat":"",
          "Cli Info:Sub_Ewwu":"",
          "Cli Info:Sub_kjlo":"",
          "Cli Info:Sub_uti":"",
          "S Funds:S_C_origin":"Afghanistan;Albania",
          "S We:Count_we":"Antigua & Barbuda;American Samoa;Austria",
          "Add Juri:Jurid_Coun":"Andorra;Angola"
         }
    
    for (const key in dataJSON) {
      if (dataJSON[key] == null) {
        delete dataJSON[key];
      }
    }
    

    Note: Feel free to add the empty string on the if statement.

    Login or Signup to reply.
  3. Use your code, have an empty object literal, and use Object.assign inside the loop as an option. Change your condition to check not-nullish values.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search