Calin Leafshade
Calin Leafshade

Reputation: 1255

How to convert an array of strings to keyed object in javascript/lodash

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

Answers (4)

Selrond
Selrond

Reputation: 3365

Using lodash:

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

_.mapValues(_.keyBy(arr), () => true);

Upvotes: 1

Tro
Tro

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

Jaromanda X
Jaromanda X

Reputation: 1

var obj = arr.reduce(function(o, v) { return o[v] = true, o; }, {});

Upvotes: 13

johnny 5
johnny 5

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

Related Questions