Files
30-seconds-of-code/snippets/pick.md
Isabelle Viktoria Maciohsek c2fdfac6ce Re-tag array snippets
2020-10-18 14:58:09 +03:00

18 lines
474 B
Markdown

---
title: pick
tags: object,intermediate
---
Picks the key-value pairs corresponding to the given keys from an object.
- Use `Array.prototype.reduce()` to convert the filtered/picked keys back to an object with the corresponding key-value pairs if the key exists in the object.
```js
const pick = (obj, arr) =>
arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
```
```js
pick({ a: 1, b: '2', c: 3 }, ['a', 'c']); // { 'a': 1, 'c': 3 }
```