4

how to append the nested object in FormData, my object is

{
    name: 'test',
    phone: '454353',
    address: [
        {
            state: 'ewrwer',
            city: 'asdasd'
        }
    ]
}

I had append like this

const data = new FormData();
data.append("name", "test");
data.append("phone", "454353");
data.append("address['state']", "ewrwer");
data.append("address['city']", "asdasd");

but this is not working for me when I send this formData in request body the address is not working.

1 Answer 1

8

It should be:

data.append("address[0]['state']", "ewrwer");
data.append("address[0]['city']", "asdasd");

Because, it is inside array of index 0, then inside that you have addresses.

Sign up to request clarification or add additional context in comments.

5 Comments

thanks for your reply is it possible to if the address is not an array just an object how to append . example address: { state: 'ewrwer', city: 'asdasd' }
Now, you can use like you did previously. data.append("address['state']", "ewrwer"); data.append("address['city']", "asdasd");
How is this not working for me. Weird
Weird, this is not working for me: In backend, I'm just getting fully string instead of json in formData. formData.append(`resources[${index}]['type']`, resource.type)
This works perfectly for me. I even used one more level of nested DTO. ` data.append("address[0].cities[0]", "FirstCity"); data.append("address[0].cities[1]", "SecondCity"); data.append("address[1].cities[0]", "SecondAddressFirstCity"); `