Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More concise way of turning an array into an object with default values? (Lodash is available)

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.

like image 304
Geesh_SO Avatar asked Oct 24 '25 23:10

Geesh_SO


1 Answers

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>
like image 135
Nina Scholz Avatar answered Oct 27 '25 14:10

Nina Scholz



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!