Skip to content

fix(keys): preserve non-plain object values like Date and RegExp#365

Open
naveentehrpariya wants to merge 1 commit into
blakeembrey:mainfrom
naveentehrpariya:fix/keys-preserve-non-plain-objects
Open

fix(keys): preserve non-plain object values like Date and RegExp#365
naveentehrpariya wants to merge 1 commit into
blakeembrey:mainfrom
naveentehrpariya:fix/keys-preserve-non-plain-objects

Conversation

@naveentehrpariya

Copy link
Copy Markdown

Fixes #356.

Problem

change-case/keys recurses into any value where typeof value === "object". That includes non-plain objects such as Date, RegExp, Map/Set and class instances. For those, it creates a new object with the same prototype and copies the own enumerable keys — but their state lives in internal slots, not enumerable keys, so the result is a broken object.

import { camelCase } from "change-case/keys";

const out = camelCase({ created_at: new Date() }, 2);
out.created_at.toISOString();
// TypeError: Method Date.prototype.toISOString called on incompatible receiver [object Object]

Fix

Only recurse into plain objects (prototype Object.prototype or null) and arrays. Any other object is returned untouched, so Date, RegExp, etc. pass through as-is.

Tests

Added cases asserting that a Date/RegExp value is preserved by reference (and remains usable), and that a non-plain object passed as the top-level value is returned untouched. Both fail without this change and pass with it; the full package suite (29 tests) stays green.

`change-case/keys` recursed into any value where `typeof === "object"`,
including `Date`, `RegExp`, `Map` and class instances. For these, copying
the (empty) own keys onto a freshly created object with the same prototype
dropped the internal state, e.g. `camelCase({ created_at: new Date() })`
produced an object whose `created_at` threw
`TypeError: Method Date.prototype.toISOString called on incompatible receiver`.

Only recurse into plain objects (and arrays); return other objects as-is.

Fixes blakeembrey#356
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

change-case/keys fails on Date objects

1 participant