Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an array to an object in Javascript without using loops?

I want to convert the following array:

['a', 'b', 'c']

to the following object:

{a: 'a', b: 'b', c: 'c'}

How do I do it without using loop, ofcourse?

like image 529
loveTrumpsHate Avatar asked Nov 30 '18 20:11

loveTrumpsHate


3 Answers

You'll want to use the Array.reduce() method.

The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value.

arr.reduce(callback[, initialValue])

The reduce() callback method takes accumulator and currentValue parameters.

  • accumulator: Value is remembered throughout each iteration of the method and ultimately becomes the final returned value.
  • currentValue: The current element being processed in the array.

The {} is supplied as the last argument to reduce() as the initial value to start with. And with each iteration of the Array, we add to it ultimately creating the final Object.

Example: (ES6)

const letters = ['a', 'b', 'c'];

const obj = letters.reduce((accumulator, currentValue) => {
  accumulator[currentValue] = currentValue;
  return accumulator;
}, {});

console.log(obj);

Example: (ES5)

var letters = ['a', 'b', 'c'];

var obj = letters.reduce(function (accumulator, currentValue) {
  accumulator[currentValue] = currentValue;
  return accumulator;
}, {});

console.log(obj);

Reference: Array.prototype.reduce() mozilla documentation.

like image 86
rootr Avatar answered Sep 22 '22 09:09

rootr


You could map objects and join to a single object with Object.assign.

var array = ['a', 'b', 'c'],
    object = Object.assign(...array.map(v => ({ [v]: v })));
    
console.log(object);
like image 26
Nina Scholz Avatar answered Sep 23 '22 09:09

Nina Scholz


An alternative solution, you can also use the newer Object.fromEntries with map as well.

let arr = ['a', 'b', 'c'];

let obj = Object.fromEntries(arr.map(m => [m,m]));

console.log(obj);
like image 25
Coola Avatar answered Sep 20 '22 09:09

Coola