I got an array from an API
const exchange = [ 'EUR', 1.19, 'USD', 1.34 ]
I am trying to transform exchange into an object
where odd index becomes the key and even index the value
{'EUR': 1.19, 'USD': 1.34}
I got an array from an API
const exchange = [ 'EUR', 1.19, 'USD', 1.34 ]
I am trying to transform exchange into an object
where odd index becomes the key and even index the value
{'EUR': 1.19, 'USD': 1.34}
Use Array.from() to create an array of [key, value] pairs, and convert the array of entries to an object using Object.fromEntries():
const fn = arr => Object.fromEntries(
Array.from({ length: Math.ceil(arr.length / 2) }, (_, i) =>
[arr[i * 2], arr[i * 2 + 1]]
)
)
const exchange = [ 'EUR', 1.19, 'USD', 1.34 ];
const obj = fn(exchange)
console.log(obj);