Search code examples
javascriptobjectsymbols

JavaScript – Get object keys in order of declaration, including symbols


In JavaScript Reflect.ownKeys() is the only function that returns both regular keys and keys that are symbols, as far as I know of at least. Other functions--for example Object.getOwnPropertyNames()--always return the keys in the order of declaration. However, with Reflect.ownKeys() the symbols are always at the end, regardless of that order.

Consider the following example:

const symbolProperty = Symbol('symbolProperty');

const object = {

    [symbolProperty]: 'Symbol Property',
    regularProperty: 'Regular Property'

};

console.log(Reflect.ownKeys(object));

// Returns 0: "regularProperty", 1: Symbol("symbolProperty")

Is there any way I can get all keys in the predictable order of declaration, like with Object.getOwnPropertyNames()? So for my example:

// 0: Symbol("symbolProperty"), 1: "regularProperty"

Please note that this should work with any object, without a separate array keeping track of the keys, or a similar "hack." If anyone knows how I can modify the array or of a different function to achieve the expected result it would be greatly appreciated.

Edit: The behavior of Object.getOwnPropertyNames() is implementation dependent, so depending on the environment it may not produce the results I observed and mentioned in this question.


Solution

  • You can iterate over the map and get keys in the order they were inserted

    const symbolProperty = Symbol('symbolProperty');
    
    const map = new Map([
        [symbolProperty, 'Symbol Property'],
        ['regularProperty', 'Regular Property']
    ]);
    
    for (const key of map.keys()) {
        console.log(key.toString()); //toString() only to show Symbol in console
    }