What is the simplest (one-line?) way to turn [1,2,3]
into {1:0, 2:0, 3:0}
?
Update: I would prefer to do it more "functional-style" (one line, with each
or map
etc)
Array reduce
method allows to pass second argument initialValue
, to the method. You can send an object as initialValue and keep returning it through the iterations, assigning properties with key set to the current item of array. Beware of type coercion, property keys must be strings in JavaScript. So toString
method will be invoked upon the items of array in this case.
var hash = array.reduce(function(obj,cur){ obj[cur]=0; return obj; },{});
In form of one liner:
var hash = array.reduce(function (obj, cur) { obj[cur] = 0; return obj; }, {});
If you just want to convert your array to a key/value object, with all values set to 0 (as in your example) then you could use:
var hash = {}; [1,2,3].forEach(function(item) { hash[item] = 0; });
Even if this is against most best practices, this seems to be neat and foremost, a one-liner
var foo = [1,2,3]; foo = eval('({' + foo.join(':0, ') + ':0 })' ); console.log( foo ); // Object {1=0, 2=0, 3=0}
eval
in this instance. But in generell, I'd agree. Its more or less a thought experiment [And therefore, no reason to downvote @anonymous]eval
is lightening fast, so is Array.prototype.join
. Performance is the least worse thing for this snippet.eval
is known to be slower, three times slower in case of the code in question – jsperf.com/flat-array-to-object I like the creativity of your answer, but the comment about it being not a real issue is something I can't agree with. It's slower, it will mess with optimisation tools, and it is harder to read.CommentedDec 18, 2012 at 15:31var arr = [1,2,3]; var result = {}; for (var i=0, l=arr.length; i<l;i++) { result[arr[i]] = 0; }
each
or map
etc)CommentedDec 18, 2012 at 14:46for(init;cond;inc)
procedure.CommentedDec 18, 2012 at 15:12Personally I don't see what's wrong with coding what you need:
function objectWithKeysAndValue(keys, value) { var o = {}; for (var i = 0, n = keys.length; i != n; ++i) { o[keys[i]] = value; } return o; } console.log(objectWithKeysAndValue([1,2,3], 0);
Out of curiosity I ran this function against Engineer's answer and it's twice as fast!
[1=>0, 2=>0, 3=>0]
{ 1: 0, 2: 0, 3: 0 }