Dimitry_N Dimitry_N - 6 months ago 16
Javascript Question

Returning an object in .each iteration - JavaScript

I have an object called

Category
which uses a method to iterate over an array of products (
Product
) and return an instance which meets the
this.name === query
condition:

function Category(products){
this.products = products;
this.findProductByName = function(query){
$(this.products).each(function(){
return this.name === query;
}
}
}


My
Product
(just in case):

function Product(name){
this.name = name;
}


I then create an instance of
Category
with products:

var $someCategory = new Category(
[
new Product('foo'),
new Product('bar')
]
)`


and when I call:

$someCategory.findProductByName('foo'); // 'undefined'


even though:

...
this.findProductByName = function(query){
$(this.products).each(function(){
console.log(this.name === query); // returns 'true'
}
}
...


What do I do to return an object when
this.name === query
is met?

Answer

You need to use a traditional loop with a return (or map/reduce) to have your function return the matched result. The each function performs an operation on each element in the array, it, won't perform filtering, and ignores the returned value.

Try this:

this.findProductByName = function(query) {
  for (var i = 0; i < this.products.length; i++) {
    if (this.products[i].name === query)
    {
      return this.products[i];
    }
  }
}

Also FYI, It's normal to pass arguments into the each() function which identify the current element being iterated over when using This helps eliminate the scope issue for 'this'

$(this.products).each(function( index, value ) {
  alert( index + ": " + value );
});
Comments