Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

83
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda