简体   繁体   中英

Object.keys but not in order JS / TS


I have a problem: I have this JSON =>

const json = {
  "test" : "...",
  "3" : "...",
  "go" : "...",
  "38" : "..."
}

And when I do:

const returned = Object.keys(json);

And returned have this inside:

3,38,go,test

In alphabetic order ! And I just want the returned in "classic" order.
Do you have a solution?

Use a Map if insertion order matters

If insertion order matters use a Map() , a map will retain the insertion order according the spec.

Demo

 let map = new Map(); map.set('test', '...'); map.set('3', '...'); map.set('go', '...'); map.set('38', '...'); for( key of map.keys() ) console.log( key )

You can use the Map object to iterate through keys in insertion order. As the MDN docs say,

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value. .... a for...of loop returns an array of [key, value] for each iteration.

If you can tolerate having leading zeros on the integer keys in the json, you could get it to work something like this:

 const json = { "test": "...", "03": "...", "go": "...", "038": "..." } console.log(Object.keys(json)) //  ["test", "03", "go", "038"] in Chrome at least

The article here explains the ordering of object keys. Essentially, integers and integer-like strings go before strings, but string go in chronological order (order of insertion). If you put a leading zero on an (string) integer, it is treated as a string, not an integer, for the purposes of ordering.

This behaviour is I think dependent on the JS engine, but it is specified I think in ES6.

You can use a little hack by adding + to object number keys like shown below and then transform them to numbers again:

const json = {
  test: "...",
  "+3": "...",
  go: "...",
  "+38": "...",
};

for (let key in json) {
  let value = json[key];
  if (key[0] === "+") {
    key = +key;
  }

  console.log(key + ": " + value);
}

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