Search code examples
javascriptlodash

Transform from string array to hashmap in Lodash


What is the most precise way to transform from this

["access","edit","delete"]

to this

{access:true, edit:true, update:true}

Currently i loop to assign each value in object but i wonder if lodash already provide function for this


Solution

  • LODASH

    You can map it to a array of entries and then simply use fromPairs of lodash

    _.fromPairs(input.map(k=>[k, true]))
    

    var input = ["access","edit","delete"];
    
    var res = _.fromPairs(input.map(k=>[k,true]));
    
    console.log(res);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

    ES6

    You can map your input to a key (your each input) value (true) pair of objects and assign them.

    Object.assign( ...input.map(k=>({[k]: true})))
    

    var input = ["access","edit","delete"]
    
    var res = Object.assign( ...input.map(k=>({[k]: true})));
    
    console.log(res);

    In case you want a Map object you can map your input to entries (as used in lodash example) and simply construct a new Map like

    new Map(input.map(k=>[k, true]))