在React Native中排序对象的对象

时间:2017-10-31 15:01:08

标签: javascript react-native

我想用对象对对象进行排序,并按日期排序。我从提供API的API中获取我的对象:

{
  "2529354": {
    "id": "2529354",
    "name": "Burton Albion-Barnsley",
    "tournament_stageFK": "850172",
    "startdate": "2017-10-31T19:45:00+00:00",
    "status_type": "notstarted",
    "status_descFK": "1",
    "n": "1",
    "ut": "2017-06-21T10:32:10+00:00",
    "tournamentFK": "11549",
    "tournament_templateFK": "48",
    "sportFK": "1",
    "tournament_stage_name": "Championship",
    "tournament_name": "2017/2018",
    "tournament_template_name": "England 2",
    "sport_name": "Soccer"
  },
  "2529355": {
    "id": "2529355",
    "name": "Cardiff City-Ipswich Town",
    "tournament_stageFK": "850172",
    "startdate": "2017-10-31T20:45:00+00:00",
    "status_type": "notstarted",
    "status_descFK": "1",
    "n": "1",
    "ut": "2017-06-21T10:32:10+00:00",
    "tournamentFK": "11549",
    "tournament_templateFK": "48",
    "sportFK": "1",
    "tournament_stage_name": "Championship",
    "tournament_name": "2017/2018",
    "tournament_template_name": "England 2",
    "sport_name": "Soccer"
  },
  "2529364": {
    "id": "2529364",
    "name": "Reading-Nottingham Forest",
    "tournament_stageFK": "850172",
    "startdate": "2017-10-31T19:00:00+00:00",
    "status_type": "notstarted",
    "status_descFK": "1",
    "n": "1",
    "ut": "2017-06-21T10:32:11+00:00",
    "tournamentFK": "11549",
    "tournament_templateFK": "48",
    "sportFK": "1",
    "tournament_stage_name": "Championship",
    "tournament_name": "2017/2018",
    "tournament_template_name": "England 2",
    "sport_name": "Soccer"
    }
};

可能很难注意到,但这3个对象的startdate不同。 API在此上下文中提供了17个对象或游戏,但它们不是有序的。我已经尝试过使用sort-function,但是对于数组来说它并没有真正起作用。

是否有可能使用Object.keys(对象)或类似的东西对其进行排序?

2 个答案:

答案 0 :(得分:1)

您无法对此对象进行排序,因为属性是键,因此无法排序。你可以将各个对象推送到一个数组中,然后对它进行排序......



var data = {
  "2529354": {
    "id": "2529354",
    "name": "Burton Albion-Barnsley",
    "startdate": "2017-10-31T19:45:00+00:00"
  },
  "2529355": {
    "id": "2529355",
    "name": "Cardiff City-Ipswich Town",
    "startdate": "2017-10-31T20:45:00+00:00"
  },
  "2529364": {
    "id": "2529364",
    "name": "Reading-Nottingham Forest",
    "startdate": "2017-10-31T19:00:00+00:00"
    }
};

var dataArray = [];

for (var i in data) {
  dataArray.push(data[i]);
}

dataArray.sort(function(x, y) {
  var xDate = new Date(x.startdate);
  var yDate = new Date(y.startdate);
  
  if (xDate < yDate) return -1
  else if (xDate > yDate) return 1
  else return 0;
});

console.log(dataArray);
&#13;
&#13;
&#13;

注意:为了显示目的,我修剪了数据。只需在使用时使用整个内容。

答案 1 :(得分:1)

你可以弄清楚键的顺序并将它们放在一个数组中:

var sortedKeys = Object.keys(data).sort((a, b) => {
    return new Date(data[b].startdate) - new Date(data[a].startdate);
});

然后您可以按照这样的排序顺序访问您的数据

sortedKeys.each(function (key) {
    // do something with data[key] 
});