Converting Array-like Objects to Arrays

suggest change

What are Array-like Objects?

JavaScript has “Array-like Objects”, which are Object representations of Arrays with a length property. For example:

const realArray = ['a', 'b', 'c'];
const 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.

However, one key difference between Arrays and Array-like Objects is that Array-like objects inherit from Object.prototype instead of Array.prototype. This means that Array-like Objects can’t access common Array prototype methods like forEach(), push(), map(), filter(), and slice():

const parent = document.getElementById('myDropdown');
const desiredOption = parent.querySelector('option[value="desired"]');
const domList = parent.children;

domList.indexOf(desiredOption); // Error: indexOf is not a method of HTMLCollection.
domList.forEach(function() {
  arguments.map(/* Stuff here */) // arguments here is this callback's own arguments object.
}); // Error: HTMLCollection has no forEach.

function func() {
  console.log(arguments);
}
func(1, 2, 3);   // looks like [1, 2, 3] in the console, but arguments is not an Array

Convert Array-like Objects to Arrays in ES6

  1. Array.from:

    const arrayLike = {
      0: 'Value 0',
      1: 'Value 1',
      length: 2
    };
    arrayLike.forEach(value => {/* Do something */}); // Errors
    const realArray = Array.from(arrayLike);
    realArray.forEach(value => {/* Do something */}); // Works
    
  2. for...of works only when the value is iterable. A plain array-like object is not, so this throws TypeError. NodeList and, in modern engines, arguments are iterable; HTMLCollection is not. Use push, not append:

    const realArray = [];
    for (const element of arrayLike) { // TypeError if arrayLike is not iterable
      realArray.push(element);
    }
    
  3. Spread has the same iterable requirement. [...arrayLike] throws on a plain array-like object.

  4. Object.values is not an array-like conversion. It includes every enumerable own value, so length is in the result (["Value 0", "Value 1", 2] for the object above), and the order is not defined as array order alone.

  5. Object.keys has the same problem: "length" is a key, so the mapped array includes 2:

    const realArray = Object
       .keys(arrayLike)
       .map((key) => arrayLike[key]);
    

Convert Array-like Objects to Arrays in ≤ ES5

Use Array.prototype.slice like so:

const arrayLike = {
  0: 'Value 0',
  1: 'Value 1',
  length: 2
};
let realArray = Array.prototype.slice.call(arrayLike);
realArray = [].slice.call(arrayLike); // Shorter version

realArray.indexOf('Value 1'); // Wow! this works

You can also use Function.prototype.call to call Array.prototype methods on Array-like objects directly, without converting them:

const domList = document.querySelectorAll('#myDropdown option');

domList.forEach(function() {
  // Do stuff
}); // NodeList has forEach in current browsers. HTMLCollection still does not.

Array.prototype.forEach.call(domList, function() {
  // Do stuff
}); // Wow! this works

You can also use [].method.bind( arrayLikeObject ) to borrow array methods and glom them on to your object:

const arrayLike = {
  0: 'Value 0',
  1: 'Value 1',
  length: 2
};

arrayLike.forEach(function() {
  // Do stuff
}); // Error! forEach is not defined.

[].forEach.bind(arrayLike)(function(val){
  // Do stuff with val
}); // Wow! this works

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

See Arrays are Objects for a detailed analysis.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents