0

I have an object like this:

  const obj = {
    a: {a: 0, b: 0},
    b: {a: 1, b: 1},
    c: {a: 2, b: 2},
    d: {a: 3, b: 3},
  };

I basically just want to move one key and its value to the first position of the object, like this:

  const obj = {
    c: {a: 2, b: 2},
    a: {a: 0, b: 0},
    b: {a: 1, b: 1},
    d: {a: 3, b: 3},
  };

I was thinking something like this:

  const { [c]: firstKeyValue, ...rest } = obj;
  const sortedObj {
        [c]: firstKeyValue,
        ...rest
      };

Any other ideas?

Samuel
  • 29
  • 3
  • Can’t do it. When you print it it will always return in that order. You can look up how it returns...but it’s like special character, numerical, alphabetical.... – Matt Dec 29 '20 at 16:02
  • 2
    Does this answer your question? [Does JavaScript guarantee object property order?](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – pilchard Dec 29 '20 at 16:03
  • You must create a new Object for that. How many keys do you have? if few and always the same, do it maually. – vsync Dec 29 '20 at 16:03
  • 4
    If you need a specific order of the elements in an object then an object on its own is not the right tool - although it could work depending on your properties. Store the properties in the correct order in an array and then access the properties of the object through that array. – Andreas Dec 29 '20 at 16:03
  • The order of the keys is determined by the order of which the keys were **first** added to the Object - afterwards, it cannot be changed without creating a new object – vsync Dec 29 '20 at 16:05
  • Your question is wrong I believe. Object properties have no guarantee of order. If you want to sort the keys/entries, then you need to first get the keys using `Object.keys` or the entries `Object.entries` respectively. You can then sort the keys/entries using the property `a` and retrieve the nested objects using the sorted keys. – Abrar Hossain Dec 29 '20 at 16:07

0 Answers0