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);
Use reduce
var arr = ['a', 'b', 'c'];
var obj = arr.reduce(function(obj, value) {
obj[value] = value;
return obj
}, {});
console.log(obj)
The object.assign() might solve your problem.
Here is an example.
var array = ['a', 'b', 'c'];
Object.assign( {}, array);
// {0: "a", 1: "b", 2: "c"}
The new object will have same index with the array.
If you want the values of the array to be same with the key.
function arrayToObject( array)
{
var object = array.reduce( (obj, value) => {
obj[value] = value;
return obj
}, {});
return object;
}
arrayToObject( ['a', 'b', 'c'])
{...['a', 'b', 'c']}results in{0: "a", 1: "b", 2: "c"}. It can't be done without map, reduce, or similar loop