Change structure of particular array in javascript

53 views Asked by At

Unfortunately, due to a plugin that I'm using, I have to serialize form names and values in a particular format for them to be saved in a database. Say I have the form:

<form>
    <input type="text" name="ratings[check-in]">
    <input type="text" name="ratings[location]">
    <textarea type="text" name="comment" placeholder=""></textarea>
    <input type="text" name="listing_id" value="9297">
</form>

currently I'm serializing this as follows:

var valueform = $('form#addmyreview').serializeArray();

which produces the following structure:

stdClass Object
(
    [0] => Array
        (
            [name] => ratings[check-in]
            [value] => 
        )

    [1] => Array
        (
            [name] => ratings[location]
            [value] => 
        )

    [2] => Array
        (
            [name] => listing_id
            [value] => 9483
        )

    [3] => Array
        (
            [name] => comment
            [value] => 
        )

)

However according to the plugin the form data has to be serialised into the following array example:

stdClass Object
(
    [ratings] => Array
        (
            [check-in] => 
            [location] => 
        )

    [listing_id] => 9297
    [comment] => wedf
)

As you can see this is far more succinct and the data can then be used by the plugin. Can anyone help with a way to serialize this object? I have tried the following:

function serializeObject(obj) {
    var jsn = {};
    $.each(obj, function() {
        if (jsn[this.name]) {
            if (!jsn[this.name].push) {
                jsn[this.name] = [jsn[this.name]];
            }
            jsn[this.name].push(this.value || '');
        } else {
            jsn[this.name] = this.value || '';
        }
    });
    return jsn;
};

but this produced:

stdClass Object
(
    [ratings[sanitation] => 
    [ratings[food] => 
    [ratings[reservation-available] => 
    [ratings[wait-time] => 
    [ratings[value] => 
    [ratings[staff-service] => 
    [listing_id] => 9483
    [comment] => 
)

so it's a big improvement but not quite there :-(

1

There are 1 answers

0
Benilson On

Use serialize instead serializeArray to post the form. The output of serialize is the same as you need in the backend.

From your output example, I assume your backend language is PHP, serialize and serializeArray are jQuery methods, where serialize is principally used for sending information by ajax, see code example below.

Form HTML:

<form id="addmyreview">
    <input type="text" name="ratings[check-in]">
    <input type="text" name="ratings[location]">
    <textarea type="text" name="comment" placeholder=""></textarea>
    <input type="text" name="listing_id" value="9297">
</form>

Javascript jQuery:

$.ajax({
    type: 'post',
    data: $('#addmyreview').serialize()
}).done(function(result) {
    // do something with result
});

In the backend PHP:

$data = (object) $_POST;