3

Given the array:

var arr = [ "one", "two", "three" ];

Whats the cleanest way to convert it to:

{ "one": true, "two": true, "three": true }

I tried the following but I imagine there is a better way.

 _.zipObject(arr || {}, _.fill([], true, 0, arr.length))
Calin Leafshade
  • 1,195
  • 1
  • 12
  • 22

4 Answers4

13
var obj = arr.reduce(function(o, v) { return o[v] = true, o; }, {});
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
  • 2
    This is the first time I've seen the comma operator on `return`. Interesting http://stackoverflow.com/questions/10284536/return-statement-with-multiple-comma-seperated-values – azium Sep 09 '15 at 14:13
0

a simple way would be like this:

function toObject(arr) {
   var rv = {};
   for (var i = 0; i < arr.length; ++i)
   rv[i] = true;
   return rv;
}
johnny 5
  • 19,893
  • 50
  • 121
  • 195
0

var array = ["one", "two", "three"];
var myObject = new Object();

for (i = 0; i < array.length; i++) {
    myObject[array[i]] = true;
}

console.log(myObject);
Tro
  • 897
  • 9
  • 32
0

Using lodash:

const arr = ['one', 'two', 'three'];

_.mapValues(_.keyBy(arr), () => true);
Selrond
  • 2,865
  • 1
  • 12
  • 9