mirror of
https://github.com/elastic/kibana.git
synced 2025-04-24 09:48:58 -04:00
@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:
parent
8a86be1143
commit
4a3b74a167
2 changed files with 36 additions and 2 deletions
35
packages/kbn-std/src/pick.test.ts
Normal file
35
packages/kbn-std/src/pick.test.ts
Normal 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' });
|
||||
});
|
||||
});
|
|
@ -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>);
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue