Home > other >  Javascript find function
Javascript find function

Time:03-29

I have an array and trying to use find method and it doesnt give be expected result but i get it via foreach. Sorry I cann't provide array, because i dont have it . I tried for a long time but didn't find a mistake. Hope its enough.

When i am using that foreach it works

products.product.forEach(function(p) {
  p.composition.id === id);
} 

But it doesnt work here

let currentProduct = products.product.find(pr=> {pr.composition.id===id});

CodePudding user response:

The reason it's not working is because you're not returning the boolean of the condition from the .find. Try this:

let currentProduct = products.product.find((pr) => {
    return pr.composition.id === id;
});

Or even just without the curly braces:

let currentProduct = products.product.find((pr) => pr.composition.id === id);
  • Related