0

The below code returns [ ] in the console:

var postdata = {};
$.each($('#form').serializeArray(), function() {
    postdata[this.name] = this.value;
}); 
var postdataarray = [];
var pnr = parseInt($("#field").val().replace("-","")); //is a number after the hyphen removed
postdataarray[pnr] = {};
postdataarray[pnr]["formdata"] = postdata;
console.log(postdataarray);

But changing var pnr to 100 just for testing returns the array/object ok. What am I not understanding?

Below is ok

var postdata = {};
$.each($('#form').serializeArray(), function() {
    postdata[this.name] = this.value;
}); 
var postdataarray = [];
var pnr = 100; //changed for testing
postdataarray[pnr] = {};
postdataarray[pnr]["formdata"] = postdata;
console.log(postdataarray);

Edit: My goal is to create an object from form data but adding a key before the form data, such as:

{"100":{formdata: {field1:value1, field2:value2, etc... } }

Kevin Lindmark
  • 1,155
  • 3
  • 13
  • 26
  • 2
    Arrays and Objects are not the same thing. `{}` is object `[]` is array. – Scott Marcus Dec 18 '20 at 21:49
  • You comments are incorrect - the value retrieved from the input element is a **String** while 100 is a primitive (Number) - they are different data types. – Randy Casburn Dec 18 '20 at 21:49
  • is not number ... check, parseInt($("#field").val().replace("-","")) – Robert Dec 18 '20 at 21:49
  • 1
    have you console.logged typeof pnr in the above snippet. I think that replace will return a string – Aalexander Dec 18 '20 at 21:50
  • What exactly is the result of `$("#field").val().replace("-","")`? Please do `console.log(JSON.stringify(pnr))` and post the output. – Bergi Dec 18 '20 at 21:56
  • @Bergi $("#field").val().replace("-","") returns a value such as 199912121234 – Kevin Lindmark Dec 18 '20 at 22:00
  • No, it doesn't. It's returning a string such as `"199912121234"`. Try this: `typeof $("#field").val().replace("-","")` to see that. – Scott Marcus Dec 18 '20 at 22:03
  • 1
    @KevinLindmark Ah. That's outside the range of [valid array indices](https://stackoverflow.com/q/12766422/1048572). – Bergi Dec 18 '20 at 22:03
  • @Bergi aha seems to be so. ParseInt and typeof shows number så I guess it is too long then... – Kevin Lindmark Dec 18 '20 at 22:05
  • @KevinLindmark There's no `parseInt` in the code you posted, so we assumed it was a string. Doesn't actually matter, though. – Bergi Dec 18 '20 at 22:06
  • @Bergi, correct. Tried with ParseInt and adjusted question above now for future reference. – Kevin Lindmark Dec 18 '20 at 22:07
  • "*Edit: My goal is to create an object*" - then, like @ScottMarcus wrote in the first comment, don't use an array there. (And don't name it `postdataarray` but `postdataobject` to avoid confusion). – Bergi Dec 18 '20 at 22:12

0 Answers0