Skip to content

Commit

Permalink
@kbn/std: fix pick method to work for objects without prototypes (#…
Browse files Browse the repository at this point in the history
…183697)

## Summary

Related to #7104
Extracted from #123748

`http2` headers are created via `Object.create(null)`, which causes
issues with the way our `pick` method was implemented. PR fixes it.
  • Loading branch information
pgayvallet committed May 17, 2024
1 parent 8a86be1 commit 4a3b74a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
35 changes: 35 additions & 0 deletions packages/kbn-std/src/pick.test.ts
Original file line number Diff line number Diff line change
@@ -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' });
});
});
3 changes: 1 addition & 2 deletions packages/kbn-std/src/pick.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@

export function pick<T extends object, K extends keyof T>(obj: T, keys: readonly K[]): Pick<T, K> {
return keys.reduce((acc, key) => {
if (obj.hasOwnProperty(key)) {
if (Object.hasOwn(obj, key)) {
acc[key] = obj[key];
}

return acc;
}, {} as Pick<T, K>);
}

0 comments on commit 4a3b74a

Please sign in to comment.