Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading