From 1a3a515ae5f87f706b4d8fa6995ca2efd9f3cc35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=CA=9C=C9=AA=E1=B4=8D=E1=B4=9C=CA=80=E1=B4=80=20Yu=CC=84?= Date: Thu, 12 Sep 2024 15:25:38 +0900 Subject: [PATCH] fix(collections): ensure `pick` doesn't generate missing properties as `undefined` (#5926) --- collections/pick.ts | 4 +++- collections/pick_test.ts | 13 +++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/collections/pick.ts b/collections/pick.ts index a443a98e8beb..c399e55624d6 100644 --- a/collections/pick.ts +++ b/collections/pick.ts @@ -28,5 +28,7 @@ export function pick( obj: Readonly, keys: readonly K[], ): Pick { - return Object.fromEntries(keys.map((k) => [k, obj[k]])) as Pick; + const result = {} as Pick; + for (const key of keys) if (key in obj) result[key] = obj[key]; + return result; } diff --git a/collections/pick_test.ts b/collections/pick_test.ts index f3604a34878b..a8a5c102a555 100644 --- a/collections/pick_test.ts +++ b/collections/pick_test.ts @@ -14,6 +14,19 @@ Deno.test({ }, }); +Deno.test({ + name: + "pick() returns a new object without properties missing in the original object", + fn() { + // deno-lint-ignore no-explicit-any + const obj = { a: 5, b: 6, c: 7, d: 8 } as any; + const picked: { a: 5; x?: 5; y?: 5 } = pick(obj, ["a", "x", "y"]); + + assertEquals(picked, { a: 5 }); + assertNotStrictEquals(picked, obj); + }, +}); + Deno.test({ name: "pick() returns a new object from the provided object with the provided keys",