Array.includes() to find object in array

前端 未结 6 972
名媛妹妹
名媛妹妹 2020-12-01 15:43

I\'m attempting to find an object in an array using Array.prototype.includes. Is this possible? I realize there is a difference between shallow and deep compari

6条回答
  •  天命终不由人
    2020-12-01 16:33

    Array.includes compares by object identity just like obj === obj2, so sadly this doesn't work unless the two items are references to the same object. You can often use Array.prototype.some() instead which takes a function:

    const arr = [{a: 'b'}]
    console.log(arr.some(item => item.a === 'b'))

    But of course you then need to write a small function that defines what you mean by equality.

提交回复
热议问题