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?
2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the input on this!
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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.