【问题标题】:Sorting API response in JSON format before passing to props in React在传递给 React 中的 props 之前以 JSON 格式对 API 响应进行排序
【发布时间】:2018-06-16 17:19:06
【问题描述】:

我试图弄清楚如何在将结果存储在组件的状态apiResults: []之前按商店名称的字母顺序对 API 响应进行排序

这是我在提交表单或单击按钮时调用的代码

getStores() {
        let userZip = this.state.userInput;
        const api = "some api";
        return fetch(api + userZip)
          .then((response) => response.json())
          .then((responseJson) => {
            //sort array alphabetically by store name
            //Add code below this line
            responseJson = sort()???
            // Add code above this line
            this.setState({
                apiResults: responseJson
            });
            console.log(this.state.apiResults);
          })
          .catch((error) => {
            console.error(error);
          });  
      }

这是我正在使用的示例 JSON。

{
    "id": "1",
    "code": "35203",
    "launch_date": "2016-01-29T00:00:00.000-05:00",
    "metro_name": "Birmingham",
    "stores": [
        {
            "id": "1",
            "name": "Target",
            "launch_date": "2018-01-24T00:00:00.000-05:00"
        },
        {
            "id": "2",
            "name": "Costco",
            "launch_date": "2017-08-14T00:00:00.000-05:00"
        },
        {
            "id": "3",
            "name": "Winn Dixie",
            "launch_date": "2018-11-29T00:00:00.000-05:00"
        },
        {
            "id": "4",
            "name": "Piggly Wiggly",
            "launch_date": "2018-04-10T00:00:00.000-05:00"
        }
    ]
}

【问题讨论】:

    标签: javascript json reactjs api


    【解决方案1】:

    这是一个示例,您可以如何做到这一点

    responseJson.stores.sort(function(a, b) {
        return (a.name.toUpperCase() < b.name.toUpperCase()) ? -1 : (a.name.toUpperCase() > b.name.toUpperCase()) ? 1 : 0;
    });
    

    看看我的codepen https://codepen.io/ulrichdohou/pen/ERbYRX?editors=0010

    【讨论】:

    • 太棒了!非常感谢你的魅力!
    • 快乐的编码兄弟
    • responseJson.stores.sort(function (a, b) { return (a.name &lt; b.name) ? -1 : (a.name &gt; b.name) ? 1 : 0; });
    • 是的,实际上是一样的。但是你的应该比我的跑得快,因为你省略了一些步骤。我会更新以使其更短
    • 没问题。我知道这应该是一些简单的事情,但我一直试图弄清楚这一点。哈哈。感谢大佬的支持。
    【解决方案2】:

    创建一个空的jsonarray对象遍历responsejson.stores并进行排序并在空数组中获取排序后的输出,然后删除存储数据并将排序后的数组推送到responsejson.stores中

    【讨论】:

      【解决方案3】:

      您可以为此使用 loadash。

      const sortedResponse = _.orderBy(responseJson, r => r.stores.name, ['asc'])
      

      【讨论】:

        猜你喜欢
        • 2019-08-31
        • 2022-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-16
        • 1970-01-01
        • 1970-01-01
        • 2019-08-11
        相关资源
        最近更新 更多