0

So I have dozens of input fields and need to parse each of them into a object with key/value pairs. I can do that easily using this here

var myobj = {};
$(this).find('.stuff').each(function (e) {
  var key = $(this).attr('name');
  var val = $(this).val();
  myobj[key] = val;
}).promise().done(function (e) {
   // do more stuff
});

However, each value is parsed as string but some of them are int and some of them are decimals. How can I parse them automatically? Do I need to add e.g. a class to each input and parse them using e.g. switch?

rst
  • 2,510
  • 4
  • 21
  • 47
  • You can use `` (along with the `step` attribute for decimals) to both control what data can be entered and let you identify if the value should be parsed as a number or not. – Lennholm Aug 07 '17 at 20:58
  • 2
    Side note, why are you making a promise off of a synchronous operation of each() ? – Taplar Aug 07 '17 at 20:59
  • possible duplicate, check https://stackoverflow.com/questions/5834901/jquery-automatic-type-conversion-during-parse-json – Shubham Aug 07 '17 at 21:02
  • @ShubhamSingla I believe not, here I don't know per se, what type I'm currently reading – rst Aug 07 '17 at 21:03
  • 1
    There are a bunch of 'is*' methods you can potentially use to check to see if the string matches various things before you parse in whatever manner you choose. http://api.jquery.com/category/utilities/ Typically markup attribute values are strings. – Taplar Aug 07 '17 at 21:06

2 Answers2

1

You could try this:

if(!isNaN(val)) {
    val = Number(val);
}

Try placing that under the line

var val = $(this).val();
  • @RobertStettler See my edit. I think that should work :) –  Aug 07 '17 at 21:04
  • Why the `, 10`? – rst Aug 07 '17 at 21:06
  • @RobertStettler Just thought, you should also need to check if val is an empty string. I don't know if that is ever something that could happen but you should still check for it. –  Aug 07 '17 at 21:10
  • @MaxO'Brien `Number()` doesn't take a second parameter, `parseInt()` does. `Number()` uses the format of the string to infer base. – Lennholm Aug 07 '17 at 21:10
  • @MikaelLennholm Ahh very true. Sorry that was a carry over from the first version I had with parseInt(). I have edited the answer now. Thanks –  Aug 07 '17 at 21:12
1

Use $.type() to test for the difference then act accordingly.

var x = 123;
var y = $.type(x);
alert(y); //alerts "number"

You can find the documentation here.

Difster
  • 3,264
  • 2
  • 22
  • 32