为何Object.groupBy()返回的对象不存在hasOwnProperty方法?
Great catch! You're absolutely right about what's happening here: the object returned by Object.groupBy() is a null-prototype object—meaning it doesn't inherit from Object.prototype, which is why calling hasOwnProperty() on it throws a TypeError. Let's break down the key reasons behind this intentional design choice:
1. Avoid key name collisions
The biggest motivation is preventing conflicts between your group keys and built-in properties/methods on Object.prototype. Imagine if one of your person objects had a role value like "hasOwnProperty" or "toString". If groupBy() returned a standard object, that key would overwrite the prototype's built-in method, making it impossible to use the original hasOwnProperty() (or any other prototype method) on the grouped object.
Using a null-prototype object eliminates this risk entirely—every key in the result is exactly the one you created via grouping, no hidden prototype properties to clash with.
2. Create a purpose-built dictionary
The grouped object is meant to act as a pure dictionary: a collection of key-value pairs where the keys are your group identifiers, and values are the matching items. Inheriting Object.prototype adds unnecessary methods (like toString(), valueOf()) that don't serve the core purpose of the grouped result.
This also makes iteration safer: when using for...in loops (though Object.keys()/Object.entries() are better practice these days), you won't accidentally iterate over prototype chain properties—you only get the groups you defined.
3. Align with modern API design patterns
This choice fits with a broader trend in JavaScript API design: moving towards more predictable, purpose-specific data structures. Null-prototype objects behave more like "true" dictionaries (similar to how Map works, but with string/symbol keys), which is exactly what you want from a grouping result.
A quick fix for checking properties
If you need to verify if a group exists, use the ES2022 Object.hasOwn() method—it's designed to safely work with null-prototype objects, as it directly checks the object's own properties without relying on the prototype chain:
console.log(Object.hasOwn(grouped, "dev")); // Returns true
Alternatively, you can explicitly call the prototype method with call():
console.log(Object.prototype.hasOwnProperty.call(grouped, "dev")); // Also works
内容的提问来源于stack exchange,提问作者PCDSandwichMan

