@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.
This commit is contained in:
Pierre Gayvallet 2024-05-17 11:11:51 +02:00 committed by GitHub
parent 8a86be1143
commit 4a3b74a167
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 36 additions and 2 deletions

View file

@ -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' });
});
});

View file

@ -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>);
}