Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

239
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda