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.
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)