Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding array elements to object's key and values

If i have the following array

const Array = ['Michael', 'student', 'John', 'cop', 'Julia', 'actress']

How could i make an object like

const Object = {
Michael: student,
John: cop, 
Julia: actress,
}

Is there a way to make the even index elements to be the object’s keys and the odd index elements to be the key’s values?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

A simple for loop that steps by two indexes at a time would work.

Try like below

const array = ['Michael', 'student', 'John', 'cop', 'Julia', 'actress'];

const output = {}

for(let i = 0; i < array.length; i+=2){
  output[array[i]] = array[i+1]
}

console.log(output);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading