Javascript Arrays
Converting Array-like Objects to Arrays
JavaScript has "Array-like Objects", which are Object representations of Arrays with a length property. For example:
var realArray = ['a', 'b', 'c'];
var arrayLike = {
0: 'a',
1: 'b',
2: 'c',
length: 3
};
Common examples of Array-like Objects are the arguments object in functions and HTMLCollection or NodeList objects returned from methods like document.getElementsByTagName or document.querySelectorAll.
Convert Array-like Objects to Arrays in ES6
1. Array.from:
const arrayLike = {
0: 'Value 0',
1: 'Value 1',
length: 2
};
const realArray = Array.from(arrayLike);
realArray.forEach(value => {/* Do something */}); // Works
2. for...of:
var realArray = [];
for(const element of arrayLike) {
realArray.append(element);
}
3. Spread operator:
[...arrayLike]
4. Object.values:
var realArray = Object.values(arrayLike);
5. Object.keys:
var realArray = Object
.keys(arrayLike)
.map((key) => arrayLike[key]);
Modifying Items During Conversion
In ES6, while using Array.from, we can specify a map function that returns a mapped value for the new array being created.
Array.from(domList, element => element.tagName); // Creates an array of tagName's