整理动态对象

时间:2019-04-26 05:44:25

标签: javascript

当前,我有一个代码并且运行正常!但是输出顺序是错误的,我尽一切努力将其整理好,但失败了。你能帮我吗?

...
var cdns_available = {};
$.ajax('https://cdn1.server.com/status.php').catch(function(e) { return done[1] = true; }).then(function(response) { cdns_available['cdn1'] = parseInt(response); done[1] = true;});
$.ajax('https://cdn2.server.com/status.php').catch(function(e) { return done[2] = true; }).then(function(response) { cdns_available['cdn2'] = parseInt(response); done[2] = true;});
$.ajax('https://cdn3.server.com/status.php').catch(function(e) { return done[3] = true; }).then(function(response) { cdns_available['cdn3'] = parseInt(response); done[3] = true;});
$.ajax('https://cdn4.server.com/status.php').catch(function(e) { return done[4] = true; }).then(function(response) { cdns_available['cdn4'] = parseInt(response); done[4] = true;});
$.ajax('https://cdn5.server.com/status.php').catch(function(e) { return done[5] = true; }).then(function(response) { cdns_available['cdn5'] = parseInt(response); done[5] = true;});

...

for (var key in cdns_available) {
    var value = cdns_available[key];
    $("#status_div").append(key + " server: " + value + "<br>");
}

输出是这样的:

cdn1 server: 50
cdn4 server: 133
cdn3 server: 28
cdn2 server: 19
cdn5 server: 117

或有时:

cdn5 server: 177
cdn4 server: 112
cdn1 server: 18
cdn2 server: 97
cdn3 server: 49

如何顺序排列“ cdn {num}”?像这样:

cdn1 server: 45
cdn2 server: 17
cdn3 server: 48
cdn4 server: 110
cdn5 server: 38

我尝试过:

Object.entries(cdns_available).sort(function(a, b) {
    return a.localeCompare(b);
});
//Error: Uncaught TypeError: a.localeCompare is not a function

你能帮我吗?谢谢。

1 个答案:

答案 0 :(得分:0)

Object.entries返回一个 arrays 数组。为了在上使用localeCompare,请访问每个数组中的第0个项目,然后进行比较:

Object.entries(cdns_available)
.sort(function(a, b) {
    return a[0].localeCompare(b[0]);
})
.forEach(([key, value]) => {
  $("#status_div").append(key + " server: " + value + "<br>");
});

但是使用Promise.all会更优雅:

Promise.all(
  [
    'cdn1',
    'cdn2',
    'cdn3'
    // ...
  ]
  .map(cdn => Promise.all([cdn, $.ajax(`https://${cdn}.server.com/status.php`)]))
)
  .then(responses => {
    responses.forEach(([cdn, response]) => {
      $("#status_div").append(cdn + " server: " + response + "<br>");
    });
  });