Si tengo la siguiente matriz
const Array = ['Michael', 'student', 'John', 'cop', 'Julia', 'actress']¿Cómo podría hacer un objeto como
const Object = { Michael: student, John: cop, Julia: actress, }¿Hay alguna manera de hacer que los elementos de índice par sean las claves del objeto y los elementos de índice impar sean los valores de la clave?
Un bucle for simple que paso por dos índices a la vez funcionaría.
Prueba como a continuación
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); 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);Puede dividir la matriz en fragmentos de tamaño 2 y luego convertirla en un objeto con 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);