0

We're serializing a form using serializeObject and then storing this into local storage as a JSON encoded string. When we decode this back out of LocalStorage, we have keys with the name of flight[inbound][0][iso] and flight[outbound][1][date] etc. This makes it difficult to properly loop through later on (in JavaScript) as we need to now repopulate the form with the stored data.

Is there a way of further decoding these key names into sub-objects? For example:

flight[outbound][0][datetime] = "Something";
flight[outbound][0][from]     = "Something";
flight[outbound][0][to]       = "Something";
flight[outbound][0][carrier]  = "Something";
flight[inbound][0][datetime]  = "Something";
flight[inbound][0][from]      = "Something";
flight[inbound][0][to]        = "Something";
flight[inbound][0][carrier]   = "Something";

Should turn into:

flight = {
    outbound: {
        0: {
            datetime: "Something",
            from:     "Something",
            to:       "Something",
            carrier:  "Something",
        }
    },
    inbound: {
        0: {
            datetime: "Something else",
            from:     "Something else",
            to:       "Something else",
            carrier:  "Something else",
        }
    }
}
James
  • 5,137
  • 5
  • 40
  • 80
  • What's the code of `serializeObject` ? This should be wrong on the step of serializing to the right object. – xdazz Apr 24 '14 at 09:54
  • I lied. It's https://gist.github.com/jbrooksuk/11248775 – James Apr 24 '14 at 09:54
  • What does the JSON look like? If your turning JSON into a JS object you should use [JSON.Parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) – Liam Apr 24 '14 at 09:55
  • @James So it's a jQuery plugin? Any way, could you create a jsfiddle to reproduce your problem? – xdazz Apr 24 '14 at 09:56
  • Also see [Javascript expando objects](http://stackoverflow.com/questions/2506005/javascript-expando-objects) `flight[outbound]` is directly equal to `flight.outbound` or `flight={outbound:{...}}` – Liam Apr 24 '14 at 10:00

1 Answers1

0

It turns out that the serializeObject plugin we're using wasn't doing the right job. Switching it for https://github.com/macek/jquery-serialize-object has provided us with what we're after.

James
  • 5,137
  • 5
  • 40
  • 80
  • 1
    You know this is build into JavaScript now don't you? You don't need a plugin at all. Also the default polyfill Json serializer is [http://bestiejs.github.io/json3/](http://bestiejs.github.io/json3/). This is the one built on JSON2 which was written by the guy who invented JSON. – Liam Apr 24 '14 at 10:12