Reputation: 1255
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))
Upvotes: 4
Views: 3215
Reputation: 3365
Using lodash
:
const arr = ['one', 'two', 'three'];
_.mapValues(_.keyBy(arr), () => true);
Upvotes: 1
Reputation: 909
var array = ["one", "two", "three"];
var myObject = new Object();
for (i = 0; i < array.length; i++) {
myObject[array[i]] = true;
}
console.log(myObject);
Upvotes: 0
Reputation: 1
var obj = arr.reduce(function(o, v) { return o[v] = true, o; }, {});
Upvotes: 13
Reputation: 21033
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;
}
Upvotes: 0