Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make object properties in console.log(obj) display alphabetically in Chrome?

It used to be that, when I used console.log(obj) to display an object's properties in Javascript, the properties would display alphabetically. Recently, this seems to have changed. I assume that the new order is closer to how the properties are actually stored in the code, (though I was under the impression that object properties didn't have a "real" fixed order to begin with).

However, for large, complex classes, the alphabetical display was very useful for finding the property that I was looking for. Is there an option for making the properties display alphabetically, as before?

(I would also like to know what exactly the current order of properties "represents" and how it is determined in the first place.)

like image 547
IndigoFenix Avatar asked Jan 02 '20 08:01

IndigoFenix


1 Answers

though I was under the impression that object properties didn't have a "real" fixed order to begin with

They do, as of ES2015 (and even operations that previously were exempt are being brought in line now), but you probably want to continue to act as though they don't. For own properties, it's the order they were added to the object (except for integer index properties which are listed in numeric order before other properties); details in the answers to this question. (There is no defined order for inherited properties, although engines are fairly consistent about what they do with them: They list them after own properties, following the same order rules. But again, that's not specified.)

Recently, this seems to have changed.

Looking at it experimentally, it looks like it's following property order now.

You could give yourself a utility function that creates a new object with the properties added to it in alphabetical order:

function logAlpha(obj) {
    const x = {};
    for (const key of Object.keys(obj).sort()) {
        x[key] = obj[key];
    }
    console.log(x);
}

Of course, unlike console.log(obj), that will be a snapshot, not a live link to the original object.

You can do a lot to tweak that (including the prototype properties, including the prototype itself, including sorted versions of the full prototype chain, etc.), but that's the gist.

like image 68
T.J. Crowder Avatar answered Nov 03 '22 22:11

T.J. Crowder