I want to save a set of ids based on a nodeList returned by a querySelector.
I achieved it with a very procedural approach, thinking in terms of steps.
- Select items
- Create an array
- Iterate over items
- Get the id
- Push it into the array
const getThem = document.querySelectorAll('.get-me');
let arrayOfData = [];
Array.prototype.forEach.call (getThem, function (node){
arrayOfData.push(node.id);
});
console.log(arrayOfData);
<ul>
<li class="get-me" id="one">One</li>
<li class="get-me" id="two">Two</li>
<li class="get-me" id="three">Three</li>
</ul>
I wonder if I can get this done with array map, to reduce the amount of lines and also take advantage of modern Javascript features.
I tried with:
const getThem = document.querySelectorAll('.get-me');
Array.prototype.map.call(getThem, (item) => ({ [id]: item.id }));
console.log(getThem);
But it doesn't work.
NodeLists don't have a.map(..)function but you can convert it to an array pretty easily, something like[...getThem]. Here is a complete example:[...getThem].map((node) => node.id)