Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

230
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!