actaeon actaeon - 5 months ago 9
jQuery Question

Using an Object as key

I'm building a questionnaire builder where the answers to some questions can lead to follow-up questions. The next step is to serialize this data and process it into a SQL query. Even though I'm using jQuery, I don't think

serializeArray()
is complex enough to serialize the data in the way I want, which would be like:

Answer = {
'text': String,
'default': String,
'img_path': String
}

Question = {
'type': String,
'text': String,
'followups': {
Answer : [Question, Question, ...],
Answer : [Question],
Answer : []
}
}


The problem I'm running into is that when I try to use an
Answer
object as a key in the
'followups'
map--when I use
JSON.stringify()
, rather than stringifying the key, it is outputted as [object Object].

EDIT:

Stringifying the key is one way to keep the data, but then there are some nasty escapes, e.g.

"followups": {
"{\"text\":\"asdfasdfa\"}": []
}


It'd be nice to fix this, but I'm open to any recommendations on a better way of serializing this form.

Answer

You will probably need to modify your data structure slightly, something similar to this:

Question = { 
    'type': String,
    'text': String,
    'followups': [
        {
            answer : Answer,
            questions : [Question, Question, ...]
        },
        {
            answer : Answer,
            questions : [Question]
        },
        {
            answer : Answer,
            questions : []
        }
    ]
}