November 4, 2023
Checking if the object is empty
Before attempting to get the first key name, it's important to verify that the object is not empty to avoid errors in your code.
Object.keys() is a method that returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop.
for...in loop iterates over the properties of an object. To get the first key, you can break the loop after the first iteration.
With ES6, you can use destructuring to extract keys into an array and then access the first element.
Reflect.ownKeys() method is used to return all keys of the object including non-enumerable and symbol keys.
Caveats to consider
- The "first" key name depends on the object's property order, which, for older ECMAScript versions, is not guaranteed.
- Non-enumerable properties won’t show up in
- Symbol properties won’t show up in
Object.keys()but will be returned by
Use case example
How to Truncate Date in MySQL