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?
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.
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.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With