-3

Is there any way to convert all undefined, NaN, etc. values in a Javascript object to a blank string (so it's at least defined).

ex: javascriptObject = defineUndefined(javascriptObject)

Something that works like that.

Jordash
  • 2,926
  • 8
  • 38
  • 77
  • Does this have to work "deep"? How many levels? I'd recommend getting a library such as [lodash](https://lodash.com/) to use for this, BUT you might find useful information here: http://stackoverflow.com/questions/14810506/map-function-for-objects-instead-of-arrays – random_user_name Feb 27 '16 at 23:07
  • What does "so it's at least defined" mean? Why do you think NaN is not defined? Which properties you want to modify (own, inherited, enumerable, data, symbols, ...)? – Oriol Feb 27 '16 at 23:09
  • 1
    Keep in mind, a blank string is still falsey, just as undefined is. So I don't really see what this is achieving – Chris Deacy Feb 27 '16 at 23:28
  • Please show what you have tried. Of course this can be done – charlietfl Feb 27 '16 at 23:44
  • 1
    Converting "all" values seems a bad idea in that it could mask or create bugs which would otherwise be easy to spot. Yet, using it very selectively to supply a default value is commonly done with an OR. See: [JavaScript OR (||) variable assignment explanation](http://stackoverflow.com/questions/2100758/javascript-or-variable-assignment-explanation) – Yogi Feb 28 '16 at 00:39

2 Answers2

0

One idea might be to check if a value is a NaN, and set that equal to 0 (or a value of your choosing).

if (isNaN(x)) x = 0;

For more information on isNaN, you can take a look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN

clasikbel
  • 39
  • 3
0
demo_object = { 
 string: 'non empty string',
 emptyString: '',
 nullString: null,
 zero: 0,
 nonZero: 10,
 negativeNumber: -10,
 undefinedValue: undefined,
 notANumber: NaN 
}

Use the below code to convert null, NAN, undefined and 0 to Blank String of demo_object.

 Object.keys(demo_object).map((key)=>{                       
  if(!demo_object[key]){    
    demo_object[key] =''    
  }
});

Below is Updated demo_object

demo_object = { 
  string: 'non empty string',
  emptyString: '',
  nullString: '',
  zero: '',
  nonZero: 10,
  negativeNumber: -10,
  undefinedValue: '',
  notANumber: '' 
}
Mohammed Ashfaq
  • 3,353
  • 2
  • 15
  • 22