I am not sure if I am missing something or that is doesnt work like I think it does. I have some form data that I want to split. To do this I thought I could create another object with the values i want to like this:
let data = $('form').serializeArray();
let answers = {};
data.forEach(function(element) {
// check if the element contains a answer input value
if(element.name.indexOf('answer') !== -1) {
answers[element.name] = element.value;
}
});
console.log($('form').serialize());
// output: answer%5B1%5D=1&answer%5B2%5D=2&answer%5B4%5D=3&answer%5B3%5D=4&sort=relevance&query=&area=..... etc
console.log(answers.serialize());
// output: is not a function.
So again. I thought you could serialize a object to a string for data storage like I do with the form data.
Can someone explain to me what i am doing wrong and/or why serialize does not work?
-
Possible duplicate of Best way to serialize/unserialize objects in JavaScript?peeebeee– peeebeee2018年08月14日 13:26:56 +00:00Commented Aug 14, 2018 at 13:26
-
@PatrickEvans That wil just convert it to a json string but not like a url params string like the serialize does. But someone answer my question, ty tho!Niels Lucas– Niels Lucas2018年08月14日 13:29:05 +00:00Commented Aug 14, 2018 at 13:29
1 Answer 1
answers is not a jQuery object so it doesn't have a serialize() method. If you wanted to get a name-value pair string like you get with jQuery's serialize then you can use jQuery's param method
answers = {
"answer1":1,
"answer2":2
};
console.log(jQuery.param(answers));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Otherwise if you are just wanting to serialize answers to JSON so that you can later recreate it then you just use JSON.stringify
answers = {
"answer1":1,
"answer2":2
};
console.log(JSON.stringify(answers));