shannonmoeller-archive / mtil

Supporting vanilla JavaScript functionality since 2014. **Unmaintained**
1 stars 0 forks source link

array/toLookup #5

Open shannonmoeller opened 10 years ago

shannonmoeller commented 10 years ago

Converts an array to an object indexed by a particular key.

var records = [
    { id: 'foo', greeting: 'hi' },
    { id: 'bar', greeting: 'howdy' },
    { id: 'baz', greeting: 'sup' }
];
var recordsIndex = records.reduce(toLookup('id'), {});
// recordsIndex === {
//     foo: { id: 'foo', greeting: 'hi' },
//     bar: { id: 'bar', greeting: 'howdy' },
//     baz: { id: 'baz', greeting: 'sup' }
// };
shannonmoeller commented 10 years ago

Multiple args for deep index, a la plucks.

https://github.com/shannonmoeller/mtil/issues/1#issuecomment-41986348

nickstark commented 10 years ago

What if lookups are not unique? Make an array?

Maybe we want a separate groupsBy or something that will deal with this.

nickstark commented 10 years ago

It also seems like this function would never be used outside of reduce due to its funky arguments signature. Maybe not a big deal, idk.

shannonmoeller commented 10 years ago

We could create the object if it doesn't exist, so that the signature is consistent:

records.reduce(toLookup('id'));