Skip to content

Instantly share code, notes, and snippets.

@teppeis
Created May 12, 2014 01:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teppeis/0f17534df07698823fe3 to your computer and use it in GitHub Desktop.
Save teppeis/0f17534df07698823fe3 to your computer and use it in GitHub Desktop.
Improvement of underscore.object()

Underscore.js http://underscorejs.org/#object (and lodash.zipObject too)

var arr = ['foo', 'bar', 'baz'];

_.object(arr);
// => {foo: true, bar: true, baz: true}

_.object(arr, 1);
// => {foo: 1, bar: 1, baz: 1}

_.object(arr, _.identity);
// => {foo: 'foo', bar: 'bar', baz: 'baz'}

_.object(arr, function(key) {return key + '!'});
// => {foo: 'foo!', bar: 'bar!', baz: 'baz!'}

Usecase:

// executed once in an initial process
var VALID_VALUES = _.object([
  'VALUE_1',
  'VALUE_2',
  ....
  'VALUE_1000'
]);

// executed many times
if (input in VALID_VALUES) {
  // do some process...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment