-2

I have the following API response:

[{
"id": 1
"name": "first Name"
"code": 100
},
{
"id": 2
"name": "second Name"
"code": 200
}]

I would like to re-order the items in the object and move "code" on the top, like this:

 [{
 "code": 100
 "id": 1
 "name": "first Name"
  },
  {
  "code": 200
  "id": 2
  "name": "second Name"
  }]
Avocado
  • 327
  • 1
  • 3
  • 16
  • 2
    [An Object is an unordered collection of properties](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – Taki Oct 01 '19 at 19:04
  • 1
    Shouldn't matter, since you are/should be accessing the properties directly by name anyway. Or, pull those ordered property names out of an array `["code","id","name"]` and display the corresponding property values in that order. – James Oct 01 '19 at 19:09

1 Answers1

1

Not sure why order should matter but the following works in Chrome:

const response = [{
    "id": 1,
    "name": "first Name",
    "code": 100
  },
  {
    "id": 2,
    "name": "second Name",
    "code": 200
}];

const reordered = response.map(i => ({
  code: i.code,
  id: i.id,
  name: i.name,
}));

console.log(reordered);
Soc
  • 7,425
  • 4
  • 13
  • 30