Rename js snippets
This commit is contained in:
21
snippets/js/s/pick-object-keys.md
Normal file
21
snippets/js/s/pick-object-keys.md
Normal file
@ -0,0 +1,21 @@
|
||||
---
|
||||
title: Pick object keys
|
||||
type: snippet
|
||||
language: javascript
|
||||
tags: [object]
|
||||
cover: compass-1
|
||||
dateModified: 2020-10-18T14:58:09+03:00
|
||||
---
|
||||
|
||||
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 }
|
||||
```
|
||||
Reference in New Issue
Block a user