Does $.getJSON reorder data?

Viewed 46

JS:

$.getJSON('services/get_locations.php', {region: $("#oblast").val()}, function(data) {
    console.log(data);
});

PHP:

$result = json_encode($raw['data']);
echo $result;
exit;

Result from var_dump($result) is:

{
    "10971":"\u0433\u0440. \u0412\u0418\u0414\u0418\u041d",
    "179":"\u0441. \u0410\u041a\u0410\u0426\u0418\u0415\u0412\u041e",
    "919":"\u0441. \u0410\u041d\u0422\u0418\u041c\u041e\u0412\u041e"
}

As you can see, first ID is 10971.

However, the result of console.log(data) is:

{179: "с. АКАЦИЕВО", 919: "с. АНТИМОВО", 10971: "гр. ВИДИН"}

Why is data being reordered?

1 Answers

Javascript objects with numeric keys will always get ordered in ascending order of the numeric key values

If order is important change structure to an array something like [{id:179, value: "...."}] or [[10971,"wrd"],[179,"xyz"]]


Example with no ajax. Note the log order is different than the constructed order (ascending key values)

const data = {
    "10971":"\u0433\u0440. \u0412\u0418\u0414\u0418\u041d",
    "179":"\u0441. \u0410\u041a\u0410\u0426\u0418\u0415\u0412\u041e",
    "919":"\u0441. \u0410\u041d\u0422\u0418\u041c\u041e\u0412\u041e"
}

console.log(data);
console.log('Keys:', Object.keys(data))

Related