Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
Convert array into an object

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}

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!