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

16,792

Solution 1

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.

Solution 2

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);

Solution 3

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);

Solution 4

You may use Array#reduce to get the desired result.

const a = ['a', 'b', 'c'];
const o = a.reduce((s, a) => {
   s[a] = a;
   return s;
}, {});

console.log(o);

Solution 5

Use reduce

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


var obj = arr.reduce(function(obj, value) {
     obj[value] = value;
     return obj
}, {});
console.log(obj)
Share:
16,792
loveTrumpsHate
Author by

loveTrumpsHate

Updated on June 08, 2022

Comments

  • loveTrumpsHate
    loveTrumpsHate almost 2 years

    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?

  • loveTrumpsHate
    loveTrumpsHate over 5 years
    Any way to do this without using map?
  • Nina Scholz
    Nina Scholz over 5 years
    why not with map?
  • loveTrumpsHate
    loveTrumpsHate over 5 years
    map is fine but something shorter using spread operator, maybe?
  • ikwuje
    ikwuje over 5 years
    @trincot thanks for mentioning. I actually thought they were the same,