8

A very basic question, but I can't find the solution :

I have a jquery object (given in console.log):

{ 
    id_ship: "1",  
    id_company: "1",  
    code: "DE",  
    // other properties...
}

I just want to get the first key on the object. In this case, i want to obtain id_ship

Thank you in advance

Rory McCrossan
  • 319,460
  • 37
  • 290
  • 318
  • 3
    You cannot guarantee the order of the properties of an object, therefore you cannot reliably retrieve the 'first' item. – Rory McCrossan Apr 28 '15 at 10:46
  • Order is only guaranteed in arrays. Would you settle for first *alphabetically-by-property-name*? – Gone Coding Apr 28 '15 at 10:47
  • http://stackoverflow.com/a/5525820/2991525 – fabian Apr 28 '15 at 10:47
  • possible duplicate of [Does JavaScript Guarantee Object Property Order?](http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – hyades Apr 28 '15 at 11:21

1 Answers1

19

As @RoryMcCrossan has said, the order in object is not guranteed. But if you still want to get first key you can use:

Object.keys(obj)[0];
Tushar
  • 82,599
  • 19
  • 151
  • 169
  • how if I have two object in array? when I want to get `id_ship` in the first object.. I try to use `Object.keys(obj[0])[0]` I try to console it and I got two.. how to get one? – Jems Dec 22 '17 at 03:14
  • @JamesRiady If you want to get the value of `id_ship`, you should use `arr[0].id_ship`. To get first key of first object in the array, use `Object.keys/(arr[0])[0]`. – Tushar Dec 22 '17 at 06:13