1

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?

Pipo
  • 5,170
  • 7
  • 33
  • 66

3 Answers3

3

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

Luke
  • 8,235
  • 3
  • 22
  • 36
1

In VanillaJS, filter is simply a method that belongs to Array, hence when you try to use filter on an object, you will get an error.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Isaac
  • 12,042
  • 16
  • 52
  • 116
  • actually we are not talking about objects here, but about those array-like objects within the dom. So in his case he is talking about `options` which is array-like and not realy an object. – Luke Jun 19 '18 at 15:41
  • @Luke Can't really understand what you mean by `array-like`, I only know there are a limited primitive `Types` in JS – Isaac Jun 19 '18 at 15:47
  • Look into NodeList. You can iterate over it, but it is not an array. it is so called array-like, because it might implement the iterator. @see https://stackoverflow.com/questions/29707568/javascript-difference-between-array-and-array-like-object – Luke Jun 19 '18 at 15:48
0

The reason is that lodash will automatically filter by keys if it's an object. Try this:

Object.keys(selectObject.options).filter( key => 
    selectObject.options[key] === 'Wanted Value');
JFord
  • 126
  • 1
  • 9