0

A Json web service returns an object like { "id": 12, "name": "xxx", "age": 12 }. How do I find out the order of the property keys or retrieve each property in the shown sequence?

I need to copy the properties into an array in the same order. This is for a generic web service, so I don't know in advance what the properties will be in the object".

Old Geezer
  • 14,854
  • 31
  • 111
  • 198
  • does Object.keys(obj) give the same order? i'm also not exactly sure – cmgchess Apr 13 '23 at 14:04
  • 1
    You can use `Object.keys()` to get the property names. However it should be noted that relying on property order is a very fragile way of coding. By nature, properties really have no order; the concept doesn't make sense because accessing properties is done by name. – Pointy Apr 13 '23 at 14:04
  • 1
    Does this answer your question? [Does JavaScript guarantee object property order?](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – 0stone0 Apr 13 '23 at 14:05
  • also https://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties might help – cmgchess Apr 13 '23 at 14:06
  • I think I will just ask the author of the web service to return the data in arrays. – Old Geezer Apr 13 '23 at 14:35
  • @OldGeezer good idea, much more stable. – Pointy Apr 13 '23 at 14:44

1 Answers1

0

const propertyOrder = ["id", "name", "age"];

const arr = [];
for (let i = 0; i < propertyOrder.length; i++) {
  const propName = propertyOrder[i];
  arr.push(obj[propName]);
}