Files
30-seconds-of-code/snippets/pick.md

14 lines
438 B
Markdown

### Pick
Use `.reduce()` to convert the filtered/picked keys back to a object with the corresponding key:value pair if the key exist in the obj.
```js
const pick = (obj, arr) => arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
// const object = { 'a': 1, 'b': '2', 'c': 3 };
// pick(object, ['a', 'c']) -> { 'a': 1, 'c': 3 }
// pick(object, ['a', 'c'])['a'] -> 1
// pick(object, ['a', 'c'])['c'] -> 3
```