object-pickby

Creates an object composed of the picked object properties. Written in Typescript for ES2019+ environments.

Usage no npm install needed!

<script type="module">
  import objectPickby from 'https://cdn.skypack.dev/object-pickby';
</script>

README

object-pickby codecov

It's similar to only or lodash.pick and lodash.pickBy, but written for today's world with TypeScript targeting Object.fromEntries supporting environments:

Contrary of all above it also works with arrays and Symbols:

import { pick, pickBy } from 'object-pickby';

it('works with symbols', () => {
  expect(
    pick({ boo: 'bar', foo: 'eee', [Symbol.for('eee')]: 'aaaa' }, [
      'boo',
      Symbol.for('eee'),
    ]),
  ).toEqual({ boo: 'bar', [Symbol.for('eee')]: 'aaaa' });
});

it('works with array and negative indexes', () => {
  expect(pick([1, 2, 3, 4], [1, -2])).toEqual([2, 3]);
});

it('picks items by function, providing accumulated array to predicate', () => {
  expect(
    pickBy(
      [1, 'slon', 2, 'slon', 3, 'foo'],
      (val, idx, acc) =>
        typeof val === 'string' && idx < 4 && !acc.includes(val),
    ),
  ).toEqual(['slon']);
});

License: MIT