I have an array, say ["a","b","c"], and I want to turn this into an object which has the array values as keys and a default value that I can set. So if the default value is true, I'd like my output to be {a:true, b:true, c:true}.
Is there a more concise version of the code below to achieve this?
var myObject = {};
["a","b","c"].forEach(x => myObject[x] = true);
I feel like there's a succinct Lodash or ES6 way to do this but I can't think of it.
Standard with Object.assign and Array#map
var array = ["a", "b", "c"],
object = Object.assign(...array.map(k => ({ [k]: true })));
console.log(object);
Or with lodash and _.set
var array = ["a", "b", "c"],
object = array.reduce((o, k) => _.set(o, k, true), {});
console.log(object);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With