add pick code snippiet

This commit is contained in:
King
2017-12-13 16:51:34 -05:00
parent 2674273efc
commit b2d737bec5

23
snippets/pick.md Normal file
View File

@ -0,0 +1,23 @@
### Pick
Use `Objexts.keys()` to convert given object to an iterable arr of keys.
Use `.filter()` to filter the given arr of keys to the expected arr of picked keys.
Use `.reduce()` to convert the filtered/picked keys back to a object with the corresponding key:value pair.
```js
const pick = (obj, arr) =>
Object
.keys(obj)
.filter((v, i) => arr.indexOf(v) !== -1 )
.reduce((acc, cur, i) => {
acc[cur] = obj[cur];
return 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
```