krmax44 krmax44 - 6 months ago 9
JSON Question

Serialized string to object

I have a serialized string like

a=4&b=2&c=7
. I need this as an object like this:
{ a:4, b:2, c:7 }
. serializeArray() just outputs a useless array like this:

[0: { name: "a", value:4 }

1: { name: "b", value:2 }]


How can I serialize a form as an object?

Thanks!

Answer

I would split the string then parse each element of the array like so :

var string = 'a=4&b=2&c=7';

var split = string.split('&') 

var newObj = {};
split.forEach(function(d, i) { 
  newObj[i] = {
    name: d.substring(0, d.indexOf('=')),
    value: d.substring(d.indexOf('=') + 1)
  }
})

console.log(newObj)

Fiddle : https://jsfiddle.net/thatOneGuy/59x3bfkL/1/

Comments