0

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?

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

let arr = ['Michael', 'student', 'John', 'cop', 'Julia', 'actress'];

let obj={};

arr.forEach((element, index) => {

  if(index % 2 === 0){

    obj[element] = arr[index+1];

  }
})

console.log(obj);

Comments

1

You could split the array into chunks of size 2 and then convert it to an object with Object.fromEntries.

let arr = ['Michael', 'student', 'John', 'cop', 'Julia', 'actress'];
let obj = Object.fromEntries([...Array(arr.length / 2)]
            .map((_, i)=>arr.slice(i * 2, i * 2 + 2)));
console.log(obj);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.