Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash convert array to object

convert array to object the output should be same as key and value.

sample array:(my input structure)

var a = [1,2,3,4,5];

I need this structure of output:

{ 
  '1': 1,
  '2': 2,
  '3': 3,
  '4': 4,
  '5': 5
}
like image 876
ragu Avatar asked May 23 '19 12:05

ragu


4 Answers

Use lodash's _.keyBy():

const result = _.keyBy([1, 2, 3, 4, 5]);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
like image 72
Ori Drori Avatar answered Nov 13 '22 02:11

Ori Drori


You don't need a library for that, just a standard reduce:

let obj = [1,2,3,4,5].reduce((o,k)=>(o[k]=k,o), {})
like image 8
Denys Séguret Avatar answered Nov 13 '22 02:11

Denys Séguret


I use reduce here

const listToObject = list => list.reduce((obj, key) => {
          return {
            ...obj,
            [key]:key
          }
        }, {})
        
console.log(listToObject([1,2,3,4,5]))
like image 4
ak85 Avatar answered Nov 13 '22 01:11

ak85


You can use Object.fromEntries() with Array.map():

var a = [1,2,3,4,5];

console.log(
Object.fromEntries(a.map(v => [v, v]))
)
like image 4
Fraction Avatar answered Nov 13 '22 00:11

Fraction