Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
like image 676
Calin Leafshade Avatar asked Oct 24 '25 02:10

Calin Leafshade


2 Answers

var obj = arr.reduce(function(o, v) { return o[v] = true, o; }, {});
like image 162
Jaromanda X Avatar answered Oct 27 '25 00:10

Jaromanda X


Using lodash:

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

_.mapValues(_.keyBy(arr), () => true);
like image 30
Selrond Avatar answered Oct 27 '25 00:10

Selrond



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!