Skip to content

fix: keep an empty-string key on unflatten instead of renaming it to 0 - #193

Open
spokodev wants to merge 1 commit into
hughsk:masterfrom
spokodev:fix-empty-string-key
Open

fix: keep an empty-string key on unflatten instead of renaming it to 0#193
spokodev wants to merge 1 commit into
hughsk:masterfrom
spokodev:fix-empty-string-key

Conversation

@spokodev

Copy link
Copy Markdown

getkey coerces a key to a number when it looks numeric, guarding only against NaN. But Number("") is 0 (not NaN), so a top-level empty-string key is turned into the index 0, which breaks the documented unflatten(flatten(obj)) round-trip:

unflatten(flatten({ "": 1, x: 2 }))   // { "0": 1, x: 2 }, expected { "": 1, x: 2 }
unflatten(flatten({ a: { "": 1 } }))  // { a: [1] }, expected { a: { "": 1 } }

flatten preserves "" losslessly (the key has no delimiter), so only unflatten corrupts it. The fix returns the empty string as-is before the numeric coercion:

function getkey (key) {
  if (key === "") return key
  const parsedKey = Number(key)
  ...
}

Numeric-index keys are unaffected (verified unflatten({"0":"a","1":"b"}) is unchanged). Full suite passes (51 + the new round-trip test); standard lint clean.

`getkey` coerces a key to a number when it is numeric, guarding only
against NaN. But `Number('')` is `0` (not NaN), so a top-level empty-string
key was turned into the index 0, breaking the documented round-trip:

    unflatten(flatten({ '': 1, x: 2 }))   // { '0': 1, x: 2 }, expected { '': 1, x: 2 }
    unflatten(flatten({ a: { '': 1 } }))  // { a: [1] }

flatten preserves `''` losslessly, so only unflatten corrupted it. Return
the empty string as-is before the numeric coercion. Added a round-trip test.
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.

1 participant