0

Lets say i have an array of objects:

let movies = [
{
    "title": "Last Flag Flying",
    "year": 2017,
    "cast": ["Steve Carell","Bryan Cranston"],
    "genres": ["Comedy","Drama"],
    "id": 1
},
{
    "title": "Lady Bird",
    "year": 2017,
    "cast": ["Saoirse Ronan","Laurie Metcalf","Tracy Letts"],
      "genres": ["Comedy","Drama"],
      "id": 2
    },
];

I want to move the last property id to the first index. I mean each of the object should start with {"id": ...} Any help would be appreciated

Jack Bashford
  • 38,499
  • 10
  • 36
  • 67
Abiud Orina
  • 597
  • 3
  • 17

2 Answers2

0

You can't. JavaScript objects are explicitly declared as unordered. Object property ordering was improved greatly in ECMAScript 6 (ES2015) but the order is still not guaranteed, especially on older versions.

If order really matters to you, then use an array - it's a specific kind of object that guarantees order, but only with its own numeric indices. If you add a non-numeric key to an array, that value may appear out of order. If you want to remember insertion order of properties (surprisingly useful) you should use a Map, also introduced in ES6.

Jack Bashford
  • 38,499
  • 10
  • 36
  • 67
0

no idea for what you might need it for but You could use a trick like:

var X = ["I'm id", "I'm x"];
X.id = X[0];
X.x = X[1];
console.log(X[0], X.id)