0

I don't understand why .include() doesn't work here when using a brand new JSON object passed as parameter. I expect b.includes({id:2,name:'a'}) returning true in all cases, here it only returns expected result when I explicitly specify array element :

const b = [{id:2,name:'a'},{id:3,name:'b'}];

b[0]
{id: 2, name: "a"}

b.includes({id:2,name:'a'});
false

b.includes({id:2,name:"a"});
false

b.includes(b[0]);
true
SCO
  • 1,832
  • 1
  • 24
  • 45
  • 4
    `Array.prototype.includes()` can only search for primitives or identical references of complex data types, because objects are only identical if their reference is the same. – connexo Apr 04 '18 at 08:53
  • 1
    `{id:2,name:'a'} === {id:2,name:'a'}` is `false` – Davin Tryon Apr 04 '18 at 08:54
  • @connexo — Not true. It can search for anything you like (subject to the normal rules of equality checking in JS). The question shows it can search for a specific object. (The limitation is that you have to search for a particular object, not an identical object) – Quentin Apr 04 '18 at 08:54
  • @Quentin Thanks for pointing that out. I tried to sharpen my comment accordingly. – connexo Apr 04 '18 at 08:55
  • 1
    @Quentin More specific duplicate target: [Javascript: Using `.includes` to find if an array of objects contains a specific object](https://stackoverflow.com/q/49187940/4642212). – Sebastian Simon Apr 04 '18 at 08:56
  • I got the point, I was missing the reference part. What is your preferred way to achieve object search then ? Iterate through the array ? – SCO Apr 04 '18 at 09:03
  • 1
    Use `.some()` or `.find()` with your own custom predicate function. – Lennholm Apr 04 '18 at 09:12
  • @MikaelLennholm Looks good to me, though these add verbosity compared to what one (at least me!) would expect from a .includes() method. Thank you ! – SCO Apr 04 '18 at 09:34
  • If you want to find your items by id (assuming id is unique) you can do: `const byID = b.reduce((o,item)=>{o[item.id]=item;return o;},{})` then you can find by id like so: `byID[someID]` – HMR Apr 04 '18 at 09:41
  • Basically I need to check that a whole object is present or not (so not only id but all fields must be checked). – SCO Apr 04 '18 at 09:43

0 Answers0