0

Let me create an object as below:

let refs = {
  'key1': {name: 'one'},
  'key2': {name: 'two'},
  'key3': {name: 'three'}
};

I want to reorder keys. For example: moving 'key2' to the last. How can I do this?

I have tried the following solution, but it doesn't effect.

let temp = refs['key2'];
delete refs['key2'];
let refsCloned = _.clone(refs);
refsCloned['key2'] = temp;

JsFiddle example

Kemal Duran
  • 1,478
  • 1
  • 13
  • 19
  • 2
    JavaScript does not guarantee the order of object keys. Therefore it makes no sense to "order" the keys. – Harun Yilmaz Sep 25 '19 at 13:10
  • 4
    Possible duplicate of [Sort JavaScript object by key](https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key) – Harun Yilmaz Sep 25 '19 at 13:10
  • 1
    Use a `Map` instead if you want it to respect order, Object doesn't guaranty order – Code Maniac Sep 25 '19 at 13:11
  • 3
    Javascript **does** in many cases guarantee a certain order for properties, which is however only manually changeable for the "in creation order" part, where i will not go into much detail, see [here](https://stackoverflow.com/a/30919039/6692606) for more info. It is **not a good idea** to rely on this order, a more fit data structure should be taken. – ASDFGerte Sep 25 '19 at 13:17
  • 1
    To do this, we must rewrite the "memory manager" of all JavaScript interpreters, while this feature does not bring any interest or benefit – Mister Jojo Sep 25 '19 at 13:22
  • 1
    @MisterJojo *some* environments actually do this. [To some extent](https://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties). There is some order introduced but not *all* environments conform to the spec and the spec might be a bit unintuitive in some respects. So it's still best not to rely on iteration order of keys in objects. – VLAZ Sep 25 '19 at 13:24

1 Answers1

0

Try this:

let refs = {
      'key1': {name: 'one'},
      'key2': {name: 'two'},
      'key3': {name: 'three'}
    };
delete refs['key2'];
const newObj = {}
newObj.key2 = {name: 'two'}
const resultObj = {...refs, ...newObj}

console.log(resultObj)
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {min-height:100% !important; top:0;}
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40