Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 978
Sarawut Positwinyu Avatar asked Oct 12 '18 04:10

Sarawut Positwinyu


People also ask

How do I turn an array into a map?

To convert an array of objects to a Map , call the map() method on the array and on each iteration return an array containing the key and value. Then pass the array of key-value pairs to the Map() constructor to create the Map object.

How do I merge two arrays in Lodash?

If both arrays are in the correct order; where each item corresponds to its associated member identifier then you can simply use. var merge = _. merge(arr1, arr2);

What is _ get?

Overview. The _. get() method in Lodash retrieves the object's value at a specific path. If the value is not present at the object's specific path, it will be resolved as undefined . This method will return the default value if specified in such a case.


1 Answers

Use reduce(). This can all be done with a simple one-liner, that doesn't require any libraries:

const input = ["access","edit","delete"];

console.log(
  input.reduce((obj, key) => { obj[key] = true; return obj; }, {})
);

With the new es6 spread syntax, you can even make this easier:

const input = ["access","edit","delete"];

console.log(
  input.reduce((obj, key) => ({...obj, [key]: true}), {})
);
like image 90
ugh StackExchange Avatar answered Sep 25 '22 16:09

ugh StackExchange