Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to properly send an array of objects to the backend using fetch?

I have an array of objects of company hierarchy that I need to send to the backend:

selectedTeams: [
  0: {team: "some_team_1", division: "some_division_1"}
  1: {team: "some_team_2", division: "some_division_2"}
  2: {team: "some_team_3", division: "some_division_3"}
]

I am trying to do the following using URLSearchParams:

const urlParams = new URLSearchParams();
urlParams.append('selected_teams', selectedTeams)
fetch(`${backendUrl}?` + urlParams)
  .then(..)

But it is null because it’s clearly not correct.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What is the proper way to do that? I can change the data types if needed (for example change it from array of objects to object of objects etc..)

>Solution :

Passing selectedTeams to append will result in [object Object], not the data you wish.

If you want to just send the objects, stringify them:

urlParams.append('selected_teams', selectedTeams.map(JSON.stringify))
const selectedTeams = [
  {team: "some_team_1", division: "some_division_1"},
  {team: "some_team_2", division: "some_division_2"},
  {team: "some_team_3", division: "some_division_3"}
]

const urlParams = new URLSearchParams();
urlParams.append('selected_teams', selectedTeams.map(JSON.stringify))

console.log('?' + urlParams)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading