0

I need to be able to rename obj keys but keep them in the same order, with my code I am able to rename the key but it's inserted after the last key :

const program = {
    "Day 1": {
      exercise: {
        exerciseType: ["you have no exercises", "please add"],
      },
    },
    "Day 2": {
      exercise: {
        exerciseType: ["push-ups", "crunches"],
      },
    },
  }


    Object.defineProperty(program, 'fire',
        Object.getOwnPropertyDescriptor(program, 'Day 1'));
    delete program['Day 1'];

console.log(program)
/* {
  Day 2: {
    exercise: { ... }
  },
  fire: {
    exercise: { ... }
  }
}
*/

https://jsfiddle.net/p4waqn26/1/

I know this question was asked before, but the solutions I found didn't work for me, maybe because my keys are in quotes.

João Pedro
  • 191
  • 1
  • 13
  • 4
    This is an object, if order matters to you then use `array` instead. – gorak Feb 12 '21 at 12:44
  • If you want to define order, you want an array of objects, not an object with nested objects defined by ordered keys – andy mccullough Feb 12 '21 at 12:45
  • AFAIK the order of keys in an object is not specified in older JavaScript standards. Different engines can behave differently. An engine could reorder it. – Thomas Sablik Feb 12 '21 at 12:46
  • The tl;dr; answer is "don't use object property order, assume properties are unordered". However, if you insist, you'll need to redo every property. Also note, that this only works, if your property is a normal string (or symbol, but not exchanging one for the other). – ASDFGerte Feb 12 '21 at 12:46
  • 1
    @ThomasSablik It is specified https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order but not a good idea to use it like this. – user202729 Feb 12 '21 at 12:46
  • @user202729 _"since ES2015"_. So older engines can use different order. _"While in ES5 explicitly no order has been specified,"_ (I changed my previous comment after I read your link) – Thomas Sablik Feb 12 '21 at 12:47
  • noone in their right mind uses IE11, and if you do, you'll run into far worse problems than property order. Also note, that full property order guarantees are only there since ES2020, while ES2015 indeed did the biggest step. – ASDFGerte Feb 12 '21 at 12:50
  • the only way is to create a new object. – Nina Scholz Feb 12 '21 at 12:50

1 Answers1

0

It the order they were inserted.

You have 'Day 1' inserted, followed by 'Day 2' followed by 'fire' You then delete 'Day 1'

Thus the order inserted is 'Day 2' and 'fire'? I see no issue with the output.

If u use 'A fire' it still give the same order.

You could create a new object and insert 'A fire' instead of 'Day 1' but insert the property in the right order. Otherwise you need to use another data structure as this one only guaranty the order of insertion in modern browser and your behavior won't work in older browser.

Pascal
  • 326
  • 1
  • 8