Ragu
Ragu

Reputation: 1728

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
}

Upvotes: 12

Views: 9629

Answers (5)

Ori Drori
Ori Drori

Reputation: 191976

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>

Upvotes: 12

Fraction
Fraction

Reputation: 12954

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

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

console.log(
Object.fromEntries(a.map(v => [v, v]))
)

Upvotes: 4

ak85
ak85

Reputation: 4264

I use reduce here

const listToObject = list => list.reduce((obj, key) => {
          return {
            ...obj,
            [key]:key
          }
        }, {})
        
console.log(listToObject([1,2,3,4,5]))

Upvotes: 5

Nina Scholz
Nina Scholz

Reputation: 386560

You could map objects with same key and value, and assign all to an object.

var array = [1, 2, 3, 4, 5],
    result = Object.assign({}, ...array.map(k => ({ [k]: k })));

console.log(result);

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382122

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), {})

Upvotes: 10

Related Questions