landau / zipmap

Returns a map with the keys mapped to the corresponding vals.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support list-of-pairs interface from Underscore

eush77 opened this issue · comments

_.object is particularly useful in the way that it is easy to apply its single-argument form to other methods' return values.

var obj = _.object('one - 1, two - 2, three - 3'
                   .split(', ')
                   .map(function (s) { return s.split(' - '); }));

Can it be part of this module as well?

commented

I'm not sure I understand what you're looking to do with zipmap. Can you show me an example?

I am looking to generate objects with zipmap.

Suppose I have an array of key-value pairs in the form of {key: 'key', value: 'value'} and I want to make a single object out of this array.

> items
[ { key: 'foo', value: 'bar' },
  { key: 'baz', value: 'quux' } ]

In its current state zipmap accepts two arguments (keys and vals), which suggests that I make these arrays first and then join them with zipmap:

> var keys = items.map(function (item) { return item.key; });
> var vals = items.map(function (item) { return item.value; });
> zipmap(keys, vals)
{ foo: 'bar', baz: 'quux' }

This is not very convenient, and I have to come up with some arbitrary names along the way. The reason is that other functions always return a single element and I can't simply “pipe” this output to zipmap.

On the other hand, you can add the one-argument form, which could make it far more convenient to generate objects on the fly. For example:

> zipmap(items.map(function (item) {
    return [item.key, item.value];
  }))
{ foo: 'bar', baz: 'quux' }
commented

These seem like good ideas.

Here is what I'll do.

  • Allow zipmap to accept a single arg
  • If that arg is an array of objects those objects must conform to key and value
  • if that arg is an array of arrays then split key/value automatically
commented

Done. Let me know what you think. Thanks!

Yay! This looks great.

One minor issue: zipmap([]) throws a TypeError, which is probably not the desired behavior (I would say returning an empty object is).

> zipmap([{ key: 'foo', value: 'bar' }].filter(function (item) {
    return item.key == 'foo';
  }))
{ foo: 'bar' }
> zipmap([{ key: 'foo', value: 'bar' }].filter(function (item) {
    return item.key == 'fo';
  }))
TypeError: Expected vals to be an array