In this fast programming era every developer face this issue including me. So I am finding best and fastest way to convert array like object into js array.
1. What is the problem?
Suppose you have a list of divs on your page and you query them via document.querySelectorAll
.
let rows = document.querySelectorAll('img')
NodeList(11)
However, rows
is not an array that you can manipulate with all of the handy array methods, like map(), filter()
etc.
That is because
NodeList
object is a list (collection) of nodes extracted from a document.
So after this the question is “What can We do?”
2. What can I do?
The easiest, fastest way to convert it into an array is just using the es6 spread operator.
let rows = document.querySelectorAll('img');
rows = [...rows]
Now, you can start applying all of the array methods to this rows
3. Other ways to solve the problem here
- use es6 spread operator […arrayLikeObject]
- usees6 Array.from(arrayLikeObject)
- [].slice.call(arrayLikeObject)
- use the good old for loop, code snippet is below, feel free to copy it, LOL
let trueArray = []
for(let i = 0; i < rows.length; i++) {
trueArray.push(rows[i])
}
If you know any other ways, feel free to leave a comment below!
Thanks for reading! ? If you find this helpful don’t forget to give some claps ?? and feel free to share this with your friends and followers! ?If you have some tips to share, feel free to comment below.
Add comment