最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to make a list from json object using React - Stack Overflow

programmeradmin8浏览0评论

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: []
    }
  }
  ponentDidMount() {
    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: []
      }
    }
    ponentDidMount() {
      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;

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: []
    }
  }
  ponentDidMount() {
    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: []
      }
    }
    ponentDidMount() {
      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;
Share Improve this question edited Jun 15, 2018 at 11:55 Kickaha asked Jun 14, 2018 at 15:41 KickahaKickaha 3,8578 gold badges41 silver badges61 bronze badges 3
  • What do you expect users to be? – Nikhil Aggarwal Commented Jun 14, 2018 at 15:46
  • @TypeError: res.data.map is not a function ... so I cant use that. I'd be happy to get any data passed into the state and I can work from there – Kickaha Commented Jun 14, 2018 at 15:51
  • You want an array of users right [{..user_object..}, {..user_object..}]? – Nikhil Aggarwal Commented Jun 14, 2018 at 16:12
Add a ment  | 

3 Answers 3

Reset to default 2

Try to parse it before with JSON.parse(res), and then you can map your array like you're doing to set your state

As far as I understood your problem is that you have an object as input and you need to convert it into an array and set it in a variable. You can use Object.values

this.setState({ users: Object.values(res.data)});

EDIT

You can improve your code as following

this.setState({ users: Object.values(res.data)});
{this.state.users.map(([UserID, Gender, Age, Occupation, ...rest]) => {
     return (
         <tr>
             <td> { UserID] } </td>
             <td> { Gender } </td>
             <td> { Age } </td>
             <td> { Occupation } </td>
             <td> { rest['Zip-Code'] } </td>
        </tr>
     )
 })}

You can use the Object.keys() method to iterate over object keys.

So you can do something similar to this:

Object.keys(res.data).map(id => res.data[id]) which will be evaluated to an array of values.

If you don't care about your keys at all, you can use Object.values() method

发布评论

评论列表(0)

  1. 暂无评论