From 4a3b74a167306e322d8f66d0381b1e87c5df6bcc Mon Sep 17 00:00:00 2001 From: Pierre Gayvallet Date: Fri, 17 May 2024 11:11:51 +0200 Subject: [PATCH] `@kbn/std`: fix `pick` method to work for objects without prototypes (#183697) ## Summary Related to https://github.com/elastic/kibana/issues/7104 Extracted from https://github.com/elastic/kibana/pull/123748 `http2` headers are created via `Object.create(null)`, which causes issues with the way our `pick` method was implemented. PR fixes it. --- packages/kbn-std/src/pick.test.ts | 35 +++++++++++++++++++++++++++++++ packages/kbn-std/src/pick.ts | 3 +-- 2 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 packages/kbn-std/src/pick.test.ts diff --git a/packages/kbn-std/src/pick.test.ts b/packages/kbn-std/src/pick.test.ts new file mode 100644 index 0000000000000..b58c8b1e9a9f8 --- /dev/null +++ b/packages/kbn-std/src/pick.test.ts @@ -0,0 +1,35 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +import { pick } from './pick'; + +describe('pick', () => { + it('works with object created inline', () => { + const obj = { foo: 'bar', hello: 'dolly' }; + + const result = pick(obj, ['foo']); + expect(result).toEqual({ foo: 'bar' }); + }); + + it('works with objects created via Object.create(null)', () => { + const obj = Object.create(null); + Object.assign(obj, { foo: 'bar', hello: 'dolly' }); + + const result = pick(obj, ['foo']); + expect(result).toEqual({ foo: 'bar' }); + }); + + it('does not pick properties from the prototype', () => { + const proto = { prot: 'o' }; + const obj = Object.create(proto); + Object.assign(obj, { foo: 'bar', hello: 'dolly' }); + + const result = pick(obj, ['foo', 'prot']); + expect(result).toEqual({ foo: 'bar' }); + }); +}); diff --git a/packages/kbn-std/src/pick.ts b/packages/kbn-std/src/pick.ts index c8347aadb219a..8d01c80caee6d 100644 --- a/packages/kbn-std/src/pick.ts +++ b/packages/kbn-std/src/pick.ts @@ -8,10 +8,9 @@ export function pick(obj: T, keys: readonly K[]): Pick { return keys.reduce((acc, key) => { - if (obj.hasOwnProperty(key)) { + if (Object.hasOwn(obj, key)) { acc[key] = obj[key]; } - return acc; }, {} as Pick); }