does include works with array of objects?

前端 未结 3 889
深忆病人
深忆病人 2021-01-28 23:24

i\'m trying to use includes to see if an object is inside the array like so:

arr=[{name:\'Dan\',id:2}]

and I want to check like so:

<         


        
相关标签:
3条回答
  • 2021-01-28 23:52

    does include works with array of objects?

    Yes — if you use the same object as the argument to includes that's in the array:

    const obj = {name: "Dan", id: 2};
    const arr = [{name: "T.J.", id: 42}, obj, {name: "Joe", id: 3}];
    console.log(arr.includes(obj));                  // true
    console.log(arr.includes({name: "Dan", id: 2})); // false

    includes uses a === check, and o1 === o2 is only ever true when o1 and o2 refer to the same object. In your example, you're using two different but equivalent objects instead.

    For your use case, you probably want some, which lets you execute a callback to determine whether an entry in the array matches a condition:

    if (arr.some(e => e.id === 2)) {
    

    Example:

    const obj = {name: "Dan", id: 2};
    const arr = [{name: "T.J.", id: 42}, obj, {name: "Joe", id: 3}];
    console.log(arr.some(obj => obj.id === 2));      // true

    There are various ways to spin that, depending on what you want the check to be (which are discussed at length in this question's answers), but that just means adjusting the contents of the function you pass some.

    0 讨论(0)
  • 2021-01-28 23:57

    Arrays do have includes() function, but for your case, you have to do using some():

    arr.some(e => e.id === 2 && e.name === "Dan")
    arr.some(e => e.name === "Dan")
    
    0 讨论(0)
  • 2021-01-29 00:04

    Not like that. Use some instead:

    arr.some(obj => obj.id === 2)
    

    Which checks if there is an object with id equals to 2.

    If you are checking for both id and name then:

    arr.some(obj => obj.id === 2 && obj.name === "Dan")
    
    0 讨论(0)
提交回复
热议问题