如何基于2列对JSON进行排序?

时间:2017-06-24 05:19:49

标签: json sorting

我贬低了JSON:

IBDesignable

并尝试先在'trip_id'列上升,然后在'location_seq'上升。在SQL中,将在查询结束时使用:

[
    {"trip_id":2, "lat":100, "lon":200, "location_seq":0},
    {"trip_id":2, "lat":200, "lon":400, "location_seq":1},
    {"trip_id":3, "lat":300, "lon":300, "location_seq":1},
    {"trip_id":3, "lat":400, "lon":400, "location_seq":0}
]

如何使用JavaScript在JSON中实现相同的功能?目标是按照trip_id和location_seq的顺序迭代上面的数据(所以最后不需要JSON - 只是为了得到正确的序列)。

感谢。

2 个答案:

答案 0 :(得分:1)

var trips = [
  {"trip_id":2, "lat":100, "lon":200, "location_seq":0},
  {"trip_id":2, "lat":200, "lon":400, "location_seq":1},
  {"trip_id":3, "lat":300, "lon":300, "location_seq":1},
  {"trip_id":3, "lat":400, "lon":400, "location_seq":0}
];

trips.sort(function(a, b) {
  if(a.trip_id !== b.trip_id)
    return a.trip_id - b.trip_id;
  return a.location_seq - b.location_seq;
});

答案 1 :(得分:1)

您可以使用以下代码。希望它会对你有所帮助。

var obj = [
{"trip_id":2, "lat":100, "lon":200, "location_seq":0},
{"trip_id":2, "lat":200, "lon":400, "location_seq":1},
{"trip_id":3, "lat":300, "lon":300, "location_seq":1},
{"trip_id":3, "lat":400, "lon":400, "location_seq":0}
]

obj.sort(function(a, b) {
    return a["trip_id"] - b["trip_id"] || a["location_seq"] - b["location_seq"];
});