4

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))
3
  • @JosephtheDreamer yes I tried: _.zipObject(sets.Seen || {}, _.fill([], true, 0, sets.Seen.length)) Commented Sep 9, 2015 at 14:13
  • Then best if you just include it in the post then. Commented Sep 9, 2015 at 14:14
  • @JosephtheDreamer Edited the Q Commented Sep 9, 2015 at 14:18

4 Answers 4

13
var obj = arr.reduce(function(o, v) { return o[v] = true, o; }, {});
Sign up to request clarification or add additional context in comments.

1 Comment

This is the first time I've seen the comma operator on return. Interesting stackoverflow.com/questions/10284536/…
1

Using lodash:

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

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

Comments

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;
}

Comments

0

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

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

console.log(myObject);

1 Comment

Don't use new Object(), use an object literal instead {}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.