简体   繁体   中英

How to sort Json data in Javascript?

I have this format of JSON data.

 {"count": 3, "records": [
 {"common":{"review_date": "2016-02-07 07:00:00","severityid": {"value": "2", "description": "Medium"}}},
 {"common":{"review_date": "2016-02-07 08:00:00","severityid": {"value": "2", "description": "Serious"}}},
 {"common":{"review_date": "2016-02-07 08:00:00","severityid": {"value": "2", "description": "Minor"}}}
 ]}

I want to see this in order of Serious,Medium and then minor.

{"count": 3, "records": [
 {"common":{"review_date": "2016-02-07 08:00:00","severityid": {"value": "2", "description": "Serious"}}},
 {"common":{"review_date": "2016-02-07 07:00:00","severityid": {"value": "2", "description": "Medium"}}},
 {"common":{"review_date": "2016-02-07 08:00:00","severityid": {"value": "2", "description": "Minor"}}}
 ]}

You can use a helper object for the wanted order.

{
    Serious: 1, 
    Medium: 2, 
    Minor: 3
}

 var data = { "count": 3, "records": [{ "common": { "review_date": "2016-02-07 07:00:00", "severityid": { "value": "2", "description": "Medium" } } }, { "common": { "review_date": "2016-02-07 08:00:00", "severityid": { "value": "2", "description": "Serious" } } }, { "common": { "review_date": "2016-02-07 08:00:00", "severityid": { "value": "2", "description": "Minor" } } }] }; data.records.sort(function (a, b) { var order = { Serious: 1, Medium: 2, Minor: 3 }; return order[a.common.severityid.description] - order[b.common.severityid.description]; }); document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM