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

233
Visualizações
How to use .map() ? I want to select querySelectorAll() + .map() to return Array with Index(name)

I need to create a variable array with index (name) = value, referring to html, example of what this array would look like:

var array = [];
array['name'] = 'value';
array['car'] = 'Ferrari';
array['car2'] = 'BMW';
array['color'] = 'Red';
console.log(array);

In my Html I'm using the .map() function to get the values but the array that is formed has an automatic index, how to define the array's index so that it is equal to the name field??

<select multiple>
      <option value="car">Ferrari</option>
Array ['car'] = 'Ferrari' ;

let list = document.querySelectorAll("option");
let items = Array.from(list).map(elem => elem.text);
console.log('items: '+items);
<select style="width:130px ;"  multiple>
     <option value="car" selected>Ferrari</option>
     <option value="car2">BMW</option>
     <option value="color">Red</option>
     <option value="color2">Black</option>
</select>

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

0

You are trying to create an object with properties, not an array. If you are coming from another language, then it may be confusing that JavaScript uses array-like syntax to access properties (called bracket notation).

You can use reduce because you are reducing multiple elements of an array to a single object:

let list = document.querySelectorAll("option");
let items = Array.from(list).reduce((acc, elem)=> {
    const value = elem.getAttribute("value");
    acc[value] = elem.text;
    return acc;
}, {});
console.log(items);
<select style="width:130px ;"  multiple>
     <option value="car" selected>Ferrari</option>
     <option value="car2">BMW</option>
     <option value="color">Red</option>
     <option value="color2">Black</option>
</select>

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