Home > Blockchain >  Adding array elements to object's key and values
Adding array elements to object's key and values

Time:03-27

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?

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

  • Related