FormData append nested object

ShibinRagh picture ShibinRagh · Sep 29, 2018 · Viewed 16.6k times · Source

Is it possible to append nested object to FormData?

let formData = new FormData();
let data = {
    title: 'title',
    text: 'text',
    preview: {p_title:'p title', p_text: 'p text'}
};

$.each(data, function(key, value) {
    formData.append(key, value);
});

Server console - console.log(req.body)

{
    title: 'title',
    text: 'text',
    preview: '[object Object]'
}

How can I get the exact value of preview: {p_title:'p title', p_text: 'p text'}?

Answer

Orest Savchak picture Orest Savchak · Sep 29, 2018

FormData values are automatically converted to string. You can try to do it using Blob.

Or just put it as string using JSON.stringify(obj).

$.each(data, function(key, value){
    if (typeof(value) === 'object') {
        value = new Blob([JSON.stringify(value)], {type : 'application/json'});// or just JSON.stringify(value)
    }
    formData.append(key, value);
});