2

Sample Code:

const a = {val: 1};
const b = {val: 2};
const list = [a, b];

console.info(list.includes(a)); // true
console.info(list.includes({val: 1})); // false

Questions:

  1. Why does the second statement evaluate as false?
  2. How can I properly use this method to search for a specific object in an array of objects?
Doug Wilhelm
  • 776
  • 9
  • 26
  • Possible duplicate of [Why can't I use Array#includes for a nested array?](https://stackoverflow.com/questions/48088657/why-cant-i-use-arrayincludes-for-a-nested-array) – Sebastian Simon Jul 09 '18 at 21:30
  • 3
    Try [Array.prototype.find()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) instead when searching for a single complex object within an array based on a predicate. – Alexander Staroselsky Jul 09 '18 at 21:31

2 Answers2

2

TL;TR

list.some(value => JSON.stringify(value) === JSON.stringify({val: 1}));

Answers:

  1. First, variable a is a reference link to object. If you checking using list.includes(a) it returns true because it found link to same object you declared previously const a = {val: 1};.

  2. Second, list.includes({val: 1}) returns false, because you are trying to search for reference to newly created object - {val: 1}. Object may contain same values and structured the same, but they store in memory as totally different objects.

If you want to check same object by structure, use Array.prototype.some() and write comparator function for your case and logic.

Firanolfind
  • 1,559
  • 2
  • 17
  • 36
2

This basically boils down to this:

{ val: 1 } === { val: 1 }  // false

Objects in javascript are compared by reference, and as the objects are at different positions in memory, they are not the same. To check for an object that has val set to 1 ypu have to manually search through all objects:

if(list.some(el => el.val === 1))
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151