我正在尝试通过制作一个简单的应用程序来学习reactjs和web开发。我的应用程序将做的是从API获取一些数据,对其进行排序并显示详细信息。我在排序响应json时遇到问题。 API网址为https://min-api.cryptocompare.com/data/all/coinlist
示例JSON响应如下:
{
"Response": "Success",
"Message": "Coin list succesfully returned!",
"BaseImageUrl": "https://www.cryptocompare.com",
"BaseLinkUrl": "https://www.cryptocompare.com",
"Data": {
"LTC": {
"Id": "3808",
"Url": "/coins/ltc/overview",
"ImageUrl": "/media/19782/ltc.png",
"Name": "LTC",
"CoinName": "Litecoin",
"FullName": "Litecoin (LTC)",
"Algorithm": "Scrypt",
"ProofType": "PoW",
"SortOrder": "2"
},
"XEC": {
"Id": "206539",
"Url": "/coins/xec/overview",
"ImageUrl": "/media/1383961/xec.png",
"Name": "XEC",
"Symbol": "XEC",
"CoinName": "Eternal Coin",
"FullName": "Eternal Coin (XEC)",
"Algorithm": "N/A",
"ProofType": "N/A",
"FullyPremined": "0",
"TotalCoinSupply": "200000000",
"PreMinedValue": "N/A",
"TotalCoinsFreeFloat": "N/A",
"SortOrder": "1486",
"Sponsored": false
},
"ONT": {
"Id": "808414",
"Url": "/coins/ont/overview",
"ImageUrl": "/media/30001663/ont.jpg",
"Name": "ONT",
"Symbol": "ONT",
"CoinName": "Ontology",
"FullName": "Ontology (ONT)",
"Algorithm": "N/A",
"ProofType": "N/A",
"FullyPremined": "0",
"TotalCoinSupply": "1000000000",
"PreMinedValue": "N/A",
"TotalCoinsFreeFloat": "N/A",
"SortOrder": "2446",
"Sponsored": false
}
...
},
"Type": 100
}
这是加密货币及其排名的详细信息。我想要实现的是在"数据"中对硬币细节进行排序。节点根据" SortOrder"值。 我怎样才能做到这一点?
答案 0 :(得分:2)
你可以像这样创建list(来自Data的数组):
var data = apiResponse.Data; // assign your data here
var arr = [];
for(let key in data){
data[key]["key"] = key;
arr.push(data[key]);
}

在此数组的JavaScript中使用sort函数,如下所示:
arr.sort(function(a,b) { return parseInt(a.SortOrder)-parseInt(b.SortOrder)});

现在,您将在arr变量中获取已排序的列表
答案 1 :(得分:0)
如果重组为数组对象,例如:
myArr = [{"Id": "3808",
"Url": "/coins/ltc/overview",
"ImageUrl": "/media/19782/ltc.png",
"Name": "LTC",
"SortOrder": "2444"
},
{"Id": "206539",
"Url": "/coins/xec/overview",
"ImageUrl": "/media/1383961/xec.png",
"Name": "XEC",
"SortOrder": "4"
},
{"Id": "808414",
"Url": "/coins/ont/overview",
"ImageUrl": "/media/30001663/ont.jpg",
"Name": "ONT",
"SortOrder": "1400"
}];
然后基于SortOrder对数组进行排序:
myarr.sort(function (a, b) {
return parseInt(a.SortOrder) - parseInt(b.SortOrder)
});
您可以直接在浏览器的JS控制台中测试ithis。