1

I have this array ["one","two","three"] would like to convert it into this {one:true, two:true, three:true}. Basically what am doing is converting the array items to keys of an object and make them boolean. I have tried using spread operator {... arr} which results to {0:'one',1:'two',2:'three'}, Any Ideas?

G B
  • 2,323
  • 3
  • 18
  • 32

3 Answers3

8

You could map objects and assign them to a single object.

var array = ["one", "two", "three"],
    object = Object.assign(...array.map(k => ({ [k]: true })));

console.log(object);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • come on. standard code with standard features. – Nina Scholz Jun 23 '18 at 17:55
  • I prefer the reduce by pointy because there is no extra conversion. You use both assign and destructuring for something simple, just to avoid the object initialisation. Then I have to go with Pointy's `var object = array.reduce((m, v) => (m[v] = true, m), {});` – mplungjan Jun 23 '18 at 17:57
  • This is also standard code with standard features: http://jsfiddle.net/mplungjan/q5e3d8cu/ :P – mplungjan Jun 23 '18 at 18:05
  • mplungjan can you please explain why it works??? – Ori Arbes Jan 30 '19 at 20:45
6

You can use .reduce():

var object = array.reduce((m, v) => (m[v] = true, m), {});

The callback function could be written as a traditional function too:

var object = array.reduce(function(m, v) {
  m[v] = true;
  return m;
}, {});

The .reduce() function passes each value in the array (v in the sample code above) to the callback, along with an "accumulator" value. The callback function can do whatever it wants to the accumulator, and then it should return it. The second argument to .reduce() is the initial value of the accumulator, in this case a new empty object.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Why reduce over a simple forEach? Saving the object initialisation? – mplungjan Jun 23 '18 at 17:49
  • @mplungjan because then I don't need a separate declaration for the target object. I personally always prefer a solution that can be written as a single expression. Of course one could wrap a `.forEach()` or even a simple `for` loop in an IIFE but that seems messy. – Pointy Jun 23 '18 at 17:51
  • Duplicate of https://stackoverflow.com/questions/4215737/convert-array-to-object which is also yours – mplungjan Jun 23 '18 at 17:51
  • @mplungjan lol :) — well it's *mostly* a duplicate I guess, except for the value requirement here. But I don't contest closing it of course. – Pointy Jun 23 '18 at 17:51
  • 1
    more lol here: http://jsfiddle.net/mplungjan/q5e3d8cu/ – mplungjan Jun 23 '18 at 18:08
1

I would simply use a forEach.

var keys = ["one","two","three"];
var obj = {};
keys.forEach(function (v) {
  obj[v] = true;
});
console.log(obj);
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252