1

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}

Luis Rodrigues
  • 329
  • 3
  • 5
  • 1
    or working off this [Converting an array into an object with key/value pairs](https://stackoverflow.com/questions/49011784/converting-an-array-into-an-object-with-key-value-pairs) – pilchard Dec 31 '21 at 14:33

3 Answers3

3

Iterate over the array and increment by 2 each time:

const exchange = [ 'EUR', 1.19, 'USD', 1.34 ];

const obj = {};
for(let i = 0; i < exchange.length - 1; i += 2) {
  const key = exchange[i], value = exchange[i+1];
  obj[key] = value;
}
  
console.log(obj);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
1

You could get the key/value pairs and build an object from it.

function* pair(array) {
     let i = 0;
     while (i < array.length) yield array.slice(i, i += 2);
}

const
    data = ['EUR', 1.19, 'USD', 1.34],
    result = Object.fromEntries([...pair(data)]);

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

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);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209