简体   繁体   中英

How to sort JSON data in ReactJS

Can anyone help me with the sorting of json data in ReactJs please? Right now it is not working properly for me. Also if i want to sort as per the title, would it be same? Thanks.

I am trying as below:

componentDidMount() 
{
        fetch('https://jsonplaceholder.typicode.com/posts').then((res) => res.json())
            .then((data) => {
                data.sort(function (a, b) {
                    return a.userId> b.userId;
                })
                data.sort();
                this.setState({data: data});

            });

    }

    render() {
        return (
            <div>
                <br/><br/>
                <br/><br/>

                < table className="table">

                    <th>User Id</th>
                    <th>Name</th>
                    <th>Address</th>
                    <th>Action</th>
                    <tbody>{this.state.data.map(function (item, key) {
                        return (
                            <tr key={key}>
                                <td>{item.userId}</td>
                                <td>{item.id}</td>
                                <td>{item.title}</td>
                                <td>{item.body}</td>
                            </tr>
                        )

                    })}</tbody>
                </table>

            </div>
        )
    }

The compareFunction in data.sort needs to return an integer, according to the docs . When comparing numbers, you can simply subtract a number from b number, in your case, a.userId - b.userId .

This code works

fetch('https://jsonplaceholder.typicode.com/posts').then((res) => res.json())
    .then((data) => {
        data.sort((a, b) => a.userId - b.userId);
        this.setState({data: data});

    });

@mshrivas, please test the following code for sorting by title :

componentDidMount()
{
  fetch('https://jsonplaceholder.typicode.com/posts').then((res) => res.json())
    .then((data) => {
      data.sort((a,b) => a.title.localeCompare(b.title));
      this.setState({data: data});
    });

}

render() {
  return (
    <div>
      <br/><br/>
      <br/><br/>

      < table className="table">

        <th>User Id</th>
        <th>Name</th>
        <th>Address</th>
        <th>Action</th>
        <tbody>{this.state.data.map(function (item, key) {
          return (
            <tr key={key}>
              <td>{item.userId}</td>
              <td>{item.id}</td>
              <td>{item.title}</td>
              <td>{item.body}</td>
            </tr>
          )

        })}</tbody>
      </table>

    </div>
  )
}

Source for localeCompare: link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM