0

So, i have a problem where my javascript is auto ordering number named arrays.

My object comes from an Ajax call, so i cant build it differently.

Example of my problem:

var test = {"1": "test1", "0": "test2", "2": "test3"}

output

console.log(test);

// {0: "teste2", 1: "teste1", 2: "teste3"}

The order should be 1,0,2...

Any way to solve this?

Btw, this is an example, in the script i am getting an object throw ajax and when i console.log it, it orders automatic, so map() functions wouldn't work here.

Lucas Martini
  • 131
  • 3
  • 20
  • Does this answer your question? [Show original order of object properties in console.log](https://stackoverflow.com/questions/39054764/show-original-order-of-object-properties-in-console-log) – Keimeno Jun 15 '21 at 12:33

2 Answers2

1

Key order is not always guaranteed with objects. The default order of properties when printing an object are as follows:

  • Integer-like keys in ascending order
  • String keys in insertion order
  • Symbols in insertion order

In your example, below, the integer-like keys are sorted numerically in the consoles JSON result.

const test = { "1": "test1", "0": "test2", "2": "test3" };

console.log(test); // {"0": "test2", "1": "test1", "2": "test3"}
.as-console-wrapper { top: 0; max-height: 100% !important; }

If you want to preserve the order of the keys, you will need to store the key order and reference it when sorting the entries inside a custom JSON stringification function. If you only want to sort by the value, this is much simpler, because there is no need for a key order array.

const test = { "1": "test1", "0": "test2", "2": "test3" };
const keyOrder = [ 1, 0, 2 ];

// Sorted by referenced key order
const customJsonStr = (obj, indent = '  ') =>
  `{\n${Object.entries(obj)
    .sort(([ka], [kb]) => keyOrder[ka] - keyOrder[kb])
    .map(([k, v]) => `${indent}"${k}": "${v}"`).join(',\n')}\n}`

// Sorted by value only
const customJsonStr2 = (obj, indent = '  ') =>
  `{\n${Object.entries(obj)
    .sort(([ka, va], [kb, vb]) => va.localeCompare(vb))
    .map(([k, v]) => `${indent}"${k}": "${v}"`).join(',\n')}\n}`

console.log(customJsonStr(test));  // {"1": "test1", "0": "test2", "2": "test3"}
console.log(customJsonStr2(test)); // {"1": "test1", "0": "test2", "2": "test3"}
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • the keys are generated automatic, i dont know them, thats why i had to use an example, i had to add a string to the number to prevent that... =/ – Lucas Martini Jun 15 '21 at 13:06
0

console.log is automatically ordering the output, your JavaScript array itself won't be ordered, unless you call the higher-order function Array.prototype.sort

Keimeno
  • 2,512
  • 1
  • 13
  • 34
  • There is no array here. What does this have to do with the question? – adiga Jun 15 '21 at 12:36
  • If i create a FOR to show an alert, it will show the wrong order either. `for (let i = 0; i < Object.keys(test).length; i++) { alert(Object.keys(test)[i]); } ` – Lucas Martini Jun 15 '21 at 12:37
  • @LucasMartini please check the duplicates at the top of the page. Integer keys are enumerated in ascending order irrespective of the order they are inserted – adiga Jun 15 '21 at 12:38
  • but its not duplicate, the object comes from an ajax call, so i cant use their answers because its a different situation, i cant simply use a map() to not order the object. – Lucas Martini Jun 15 '21 at 12:40