Search code examples
javascriptecmascript-5

Why lodash _.filter method works on select options but not vanilla js 's filter method?


When I want to use js es 5 filter method on options object, code bellow triggers an error

var selectObject = element.querySelector(".selectorClass");
let defaultOption = selectObject .options.filter(option => {
         return option.value === "Wanted Value";
    })[0];

JavaScript runtime error: Object doesn't support property or method 'filter'

However if I try the same code with _lodash everything works fine

  var selectObject = element.querySelector(".selectorClass");
  var defaultOption = _.filter(selectObject .options, (option: any) => {
         return option.value === "Wanted Value";
  })[0];

Do you know why and possibly how to use filter on select options in ecma script 5 please?


Solution

  • In some cases, in DOM you will receive something that looks like an array, but in fact it is not. So in your case options is array-like, a HTMLOptionsCollection. To learn more about those objects, see this question

    To fix this, you can slice it to an actual array

    const myOptions = Array.prototype.slice.call(selectObject.options)
    

    see https://hackernoon.com/htmlcollection-nodelist-and-array-of-objects-da42737181f9

    if you are using es6, you could also use following.

    // Spread operator
    [...selectObject.options].forEach(callback);
    
    // Array.from()
    Array.from(selectObject.options).forEach(callback);
    
    // for...of statement
    for (var option of selectObject.options) callback(option);
    

    credit goes to this gist