José Carlos
José Carlos

Reputation: 774

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?

Upvotes: 0

Views: 67

Answers (3)

Unmitigated
Unmitigated

Reputation: 89517

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

Upvotes: 1

Salwa A. Soliman
Salwa A. Soliman

Reputation: 746

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

Upvotes: 1

Amila Senadheera
Amila Senadheera

Reputation: 13265

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

Upvotes: 3

Related Questions