-2

I have array that contains object like this:

products: [{
 title: 'this is title',
 id: 1
 },
 title: 'this is another product',
 id: 2
}]

I want to check if products include id: 1.

Here is my try:

arr.includes(products[id, product.id])

but it's not working.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
sid heart
  • 1,140
  • 1
  • 9
  • 38
  • Firstly did you check what `products[id, product.id]` is? Secondly, includes with an object is likely not to work because they have to be _the exact same object instance_ to match, not just have the same props. – jonrsharpe Apr 18 '21 at 08:40
  • Please visit [help], take [tour] to see what and [ask]. ***>>>[Do some research](https://www.google.com/search?q=javascript+includes+object+array+site:stackoverflow.com)<<<***, search for related topics on SO; if you get stuck, post a [mcve] of your attempt, noting input and expected output, preferably in a [Stacksnippet](https://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/). – mplungjan Apr 18 '21 at 08:41

1 Answers1

2

You need to iterate the array and check the property.

const
    includes = (array, key, value) => array.some(o => o[key] === value),
    products = [{ title: 'this is title', id: 1 }, { title: 'this is another product', id: 2 }];
    
console.log(includes(products, 'id', 1));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392