Skip to content

Commit

Permalink
Add Object.pick
Browse files Browse the repository at this point in the history
  • Loading branch information
gilbert committed Mar 6, 2017
1 parent 8d8821f commit 1d44bb7
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,28 @@ This is useful when you want a quick debug on callback, such as a promise:
```js
fetchItems().then( inspect('items') )
```

### `object/pick`

Makes available the `Object.pick` function, which picks an array of properties from a given object.

```js
var original = { x: 10, y: 20, z: 30 }

var picked = Object.pick(['x', 'z'], original)
picked //=> { x: 10, z: 30 }
```

If you only give the first argument `Object.pick`, then it returns a function that expects the second argument:

```js
var pick2dCoords = Object.pick(['x', 'y'])

pick2dCoords({ x: 10, y: 20, z: 30 }) //=> { x: 10, y: 20 }

arrayOfCoords.map( pick2dCoords ) // Another example


fetchItem()
.then( Object.pick(['name', 'price']) ) // Inline usage
```
18 changes: 18 additions & 0 deletions object/pick.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@

Object.pick = function pick (properties, obj) {
if (arguments.length === 1) {
return function (obj) { return _pick(properties, obj) }
}
return _pick(properties, obj)
}

function _pick (properties, obj) {
var result = {}

for (var i=0; i < properties.length; i++) {
var prop = properties[i]
result[prop] = obj[prop]
}

return result
}

0 comments on commit 1d44bb7

Please sign in to comment.