I am sending data via fetch to the server with FormData(), both JSON data and files. I receive a JSON object with the files, and I update with FormData.append() like this.
var data = {
    title: 'A title',
    img: 'https://fakeimg.pl/500x500/',
    description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
};
let formData = new FormData();
for (var key in data) {
    formData.append(key, data[key]);
}
This works, but only in the first level of the JSON object. And I need to send arrays of data inside my object, which can have files (I will represent the files with {...}):
var data = {
        title: 'A title',
        img: 'https://fakeimg.pl/500x500/',
        description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
        images: [
            { img: 'https://fakeimg.pl/500x500/', imgFile1: {...} },
            { img: 'https://fakeimg.pl/500x500/', imgFile2: {...}  },
            { img: 'https://fakeimg.pl/500x500/', imgFile3: {...}  },
            { img: 'https://fakeimg.pl/500x500/', imgFile4: {...}  },
        ],
    };
I wrote this function:
function iterateObject(object) {
    for (var key in object) {
        if (Array.isArray(object[key])) {
            object[key].map((item) => {
                iterateObject(item);
            });
        } else if (typeof object[key] === 'object') {
            iterateObject(object[key]);
        } else {
            formData.append(key, object[key]);
        }
    }
}
iterateObject(data);
But in the server I end up with:
{
    title: 'A title',
    img: [
        'https://fakeimg.pl/500x500/',
        'https://fakeimg.pl/500x500/',
        'https://fakeimg.pl/500x500/',
        'https://fakeimg.pl/500x500/',
        'https://fakeimg.pl/500x500/',
    ],
    description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
    images: '[object Object],[object Object],[object Object],[object Object]',
};
Does anyone know how to update this object properly, no matter the amount of nesting?
 
    