Use call on Reduce to apply it to array likes

This commit is contained in:
Robert Mennell
2018-05-31 10:56:07 -07:00
committed by GitHub
parent de3f900b34
commit 01a3266fac

View File

@ -1,10 +1,12 @@
### toHash
Reduces a given iterable type into a value hash(Object by reference) by the given property or the current iteration
Reduces a given Array Like into a value hash(keyed data store)
Given an Iterable or Array like structure we call Array.prototype.reduce.call on the provided object to step over it and return an Object keyed by the reference value
```js
const toHash = ( object, key ) =>
object.reduce( ( acc, data, index ) => ( ( acc[ data[ key || index ] ] = data ), acc ), {} )
Array.prototype.reduce.call( object, ( acc, data, index ) => ( ( acc[ !key ? index : data[ key ] ] = data ), acc ), {} ) )
```
```js
@ -14,7 +16,7 @@ toHash([ { a: 'label' } ], 'a'); // { label: { a: 'label' } }
// A more in depth example
let users = [ { id: 1, first: 'Jon' }, { id: 2, first: 'Joe' }, { id: 3, first: 'Moe' } ];
let managers = [ { manager: 1, employees: [ 2, 3 ] } ];
// We use function here because we need a bindable reference
// We use function here because we want a bindable reference but a closure referencing the hash would work too
managers.forEach( manager =>
manager.employees = manager.employees.map(
function( id ){