I'm gettin Json object like this from a service
{"0":{"UserID":1,"Gender":"F","Age":1,"Occupation":10,"Zip-code":48067},
"1":{"UserID":2,"Gender":"M","Age":56,"Occupation":16,"Zip-code":70072},
"2":{"UserID":3,"Gender":"M","Age":25,"Occupation":15,"Zip-code":55117},
"3":{"UserID":4,"Gender":"M","Age":45,"Occupation":7,"Zip-code":2460},"4":}
Then using React am trying to map it to a state, but it's an object not an array of objects
class App extends Component {
constructor() {
super();
this.state = {
users: []
}
}
componentDidMount() {
this.getUsers();
};
getUsers() {
axios.get(`${SERVICE_URL}/users`)
.then((res) => {
console.log(res.data); // I can see the data in the console
this.setState({ users: res.data.map((data) => {return (data.key, data.value)} }); })
.catch((err) => { console.log(err); });
}
I though something like this might work, but no.
this.setState({ users: res.data.ToArray().map((data) => {return (data.key, data.value)})})})
Final update, this is what worked. (probably still cleaner way but this works)
class App extends Component {
constructor() {
super();
this.state = {
users: []
}
}
componentDidMount() {
this.getUsers();
};
getUsers() {
axios.get(`${SERVICE_URL}/users`)
.then((res) => {
this.setState({ users: Object.values(JSON.parse(res.data))});
})
.catch((err) => { console.log(err); });
}
render() {
return (
<div>
<table class='userList'>
<tr>
<td>UserId</td>
<td>Gender</td>
<td>Age</td>
<td>Occupation</td>
</tr>
{this.state.users.map(({UserID, Gender, Age, Occupation}) => {
return (
<tr key={'user'+UserID}>
<td> { UserID } </td>
<td> { Gender } </td>
<td> { Age } </td>
<td> { Occupation } </td>
</tr>
)})}
</table>
</div>
);
}
}
export default App;
[{..user_object..}, {..user_object..}]?