typescript convert array to object code example
Example 1: convert array to object javascript
const convertArrayToObject = (array, key) =>
array.reduce(
(obj, item) => ({
...obj,
[item[key]]: item
}),
{}
);
Example 2: javascript convert array to object
function arrayToObject(arr) {
var obj = {};
for (var i = 0; i < arr.length; ++i){
obj[i] = arr[i];
}
return obj;
}
var colors=["red","blue","green"];
var colorsObj=arrayToObject(colors);
Example 3: js array to object with keys
const arr = ['a','b','c'];
const res = arr.reduce((a,b)=> (a[b]='',a),{});
console.log(res)