Array.includes() to find object in array

前端 未结 6 968
名媛妹妹
名媛妹妹 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:13

    You are on the right track but, the issue is the difference between reference and value types, you currently are using a reference type (object literal), so when you compare what is in the array with what you have, it will compare the references and not the values. this is what I mean:

        var ar = [];
        var x = {a: "b", c: "d" };
        ar.push(x);
    
        // this will log true because its the same reference
        console.log("should be true: ", ar[0] === x);
    
        ar.push({a: "b", c: "d" });
        // this will log false because i have created 
        // a different reference for a new object.
        console.log("should be false: ", ar[1] === x);
        
        // Think of it like this
        var obja = { foo: "bar" }; // new reference to 'obja'
        var objb = { foo: "bar" }; // new reference to 'objb'
        var valuea = 23;
        var valueb = 23;
        
        // 'obja' and 'obja' are different references
        // although they contain same property & value
        // so a test for equality will return false
        console.log("should be false: ", obja === objb);
    
        // on the other hand 'valuea' and 'valueb' are 
        // both value types, so an equality test will be true
        console.log("should be true: ", valuea === valueb);

    to achieve what you want, you either have to have added the actual reference, as I did above, or loop through the array and compare by unique property of the objects.

提交回复
热议问题