Skip to content

Instantly share code, notes, and snippets.

@johnsmith17th
Last active December 16, 2015 19:50
Show Gist options
  • Save johnsmith17th/5487897 to your computer and use it in GitHub Desktop.
Save johnsmith17th/5487897 to your computer and use it in GitHub Desktop.
Convert array to object, each element of array is as a key in object, and ignores the non-string elements.
var util = require('util');
/**
* Convert array to object,
* each element of array is as key in object,
* and ignores the non-string elements.
*
* @example
* [ 'a', 'b', 'c' ] => { 'a':1, 'b':1, 'c':1 }
*
* @param arr{Array}
* @returns {Object}
*/
function objectify(arr) {
var s = {}, x;
if (util.isArray(arr)) {
for (var i = 0; i < arr.length; i++) {
x = arr[i];
if ('string' == typeof(x)) {
s[x] = 1;
};
};
};
return s;
};
//test
//console.log(objectify(['a', 'b', 'c']));
module.exports = objectify;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment