A couple weeks ago I had an issue…I needed to send the number values contained in an object to the server as integers. The only catch was, I didn’t know how many elements were in the object or which ones were supposed to be integers and which were supposed to be strings. I could however trust that the values in the object were appropriate for each key.

I ended coming up with a little hack using some of JavaScripts type coercion to get the results I needed.

var parsed;
Object.keys(values).forEach(function(key) {
  parsed = parseInt(values[key], 10);
  if (values[key] == parsed) {
    values[key] = parsed;
  }
});

So what’s happening here?

Object.keys(values).forEach(function(key) {

I am using the Object.keys() method to get the keys of each element in an array and then looping over them using Array.prototype.forEach() instead of using a for loop.

parsed = parseInt(values[key], 10);

In the loop I parseInt every value and store it in a temporary variable.

if (origVal == parsed) {
  values[key] = parsed;
}

Now I compare the parsed value to the original value allowing JavaScript to do it’s type coercion and if they are equal then I overwrite the original value with the parsed value, else I continue on to the next element. This works because parseInt(“2”, 10) === 2 and 2 == “2” but parseInt(“2Foo”, 10) === 2 and 2 != “2Foo”. You can see a working example here.

Although this has a fairly limited use case I hope you found the technique interesting albeit a little bit of a hack. Thanks for reading!