Alexander Abramovich
Alexander Abramovich

Reputation: 11438

How to create a hash from array

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)

Upvotes: 2

Views: 649

Answers (5)

Ja͢ck
Ja͢ck

Reputation: 173562

Personally 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!

Results

Upvotes: 0

Cyril F
Cyril F

Reputation: 1882

var arr = [1,2,3];

var result = {};
for (var i=0, l=arr.length; i<l;i++) {
    result[arr[i]] = 0;
}

Upvotes: 0

Engineer
Engineer

Reputation: 48793

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;
},{});

demo

In form of one liner:

var hash = array.reduce(function (obj, cur) { obj[cur] = 0; return obj; }, {});

Upvotes: 4

jAndy
jAndy

Reputation: 236012

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}

Upvotes: 0

nekman
nekman

Reputation: 1919

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;
});

Upvotes: 0

Related Questions