Map array and find values

Viewed 729

I have an array and an object. In the array I have a list of Products and in the object I have a category.

What I should to do is to find a code in the array equals to the category.Code .

So I have thought to do a .map of the array, but I don't know how to return back only the values equal to category.code.

console.log("this.props.products: ", this.props.products)
console.log("this.props.category: ", this.props.category)

let findProducts = this.props.products.Products.map((product) => {
    console.log("product_", product.Categories.MainCode)
    product.Categories.MainCode == this.props.category.Code
})

console.log("findProducts: ", findProducts)

The findProducts returns me a list of undefined.

Basically I want obtain only the this.props.products.Products.Categories.MainCode == this.props.category.Code

(that should be more than one).

How can I do?? Thank you

6 Answers

map is not the right function to use in this case. Instead, use .filter() function which will return an array of only those products for which the callback function returns true

let findProducts = this.props.products.Products.filter((product) => {
  return product.Categories.MainCode == this.props.category.Code;
})

What you need in this case is array.filter method, which expects a function to decide if an element should be in the result array.

let findProducts = this.props.products.Products.filter((product) => {
    return product.Categories.MainCode === this.props.category.Code
})
``

Try with filter

var arrayFiltered = this.props.products.Products.filter(item => item.Categories.MainCode == this.props.category.code);

You also need to return something from that mapping lambda...

let findProducts = this.props.products.Products.map(product => {
  console.log('product_', product.Categories.MainCode);
  return product.categories.MainCode == this.props.category.Code;
});

Besides, it looks like a use case for .filter rather than .map.

This sounds like a standard use of filter:

let findProducts = this.props.products.Products.filter((product) => {
   return product.Categories.MainCode == this.props.category.Code
})

Filter returns only the entries for which true is returned.

Try this:

let findProducts = this.props.products.Products.map((product) => {
    if (product.Categories.MainCode === this.props.category.Code) return product
})

Related