5

I have dependents array, which has multiple objects. I need to send that array of objects through form data. I have gone through so many tries but cannot get correct solution

    let dependents = [{name: "ashraf", number: 96546},{name: "himanshu", number: 98766}]

I was trying to append using

    var data = new FormData();
    data.append("dependents[]", dependents)

1
  • Use dependents.concat(name of array to append), concat returns the new array. Commented Aug 22, 2019 at 7:51

2 Answers 2

7

You can use Array#forEach to accomplish this... however your array elements will be stringified obejcts.

const dependents = [{name: "ashraf", number: 96546},{name: "himanshu", number: 98766}]
const data = new FormData();
dependents.forEach(item => {
  data.append(`dependents[]`, JSON.stringify(item));
});
console.log(data.getAll('dependents[]'));

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

Comments

2

I like this:

const dependents = [{name: "ashraf", number: 96546},{name: "himanshu", number: 98766}]
const data = new FormData();

dependents.forEach((item, index) => {
  data.append(`dependents[${index}]name`, item['name']);
  data.append(`dependents[${index}]number`, item['name']);
});

And then when you receive the data, do something like this:

params['dependents'].values

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.