Home > Enterprise >  Convert array into an object
Convert array into an object

Time:01-01

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}

CodePudding user response:

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);

CodePudding user response:

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);

CodePudding user response:

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);

  • Related