I have the following JSON data being returned, but for some reason, Javascript or jQuery ajax seems to re-organise the items list. The server returns the data sorted alphabetically by item.title (verified)…
The JSON below is after the ordering has been butchered:
{
"count": 3,
"items": {
"tardis": {
"type": 40,
"title": "Tardis",
"timeMachine": true,
"reliable": true
},
"stargate": {
"type": "Milky way gate",
"title": "Stargate + solar flare",
"timeMachine": true,
"reliable": false
}
}
}
Does anyone why the ordering is being tampered with? How can I re-order the items byt the title value?
Your
itemsobject is not an array, but just an object with named members. These members have no inherent order.For instance, doing a
console.log({ your object })in chrome will yield the properties sorted by the member name, in this case “stargate” and “tardis”, in that order. But writingfor(k in x.items) console.log(k)for the exact same object, will (in Chrome – again, no reliable specification here) iterate over the objects in the order they were defined, and log “tardis”, “stargate”.This ordering is an artifact of how an object is presented, not of the object itself. Use arrays if you want ordering: