Home > Blockchain >  How to use .map() ? I want to select querySelectorAll() .map() to return Array with Index(name)
How to use .map() ? I want to select querySelectorAll() .map() to return Array with Index(name)

Time:06-16

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>

CodePudding user response:

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>

  • Related