0

Currently I have an array like this:

const selected = [{a: 'john', b: 12}, {a: 'Paul', b: 12}]

And I want to set a constant called isSelected that be true if some object exists in that array.

Example:

const obj = {a: 'Paul', b: 12}

That object exists in the array.

I wanted to check it with:

const isSelected = selected.some((item) => item === obj);

Is not working, every items seems not be === to obj. I guess that some use a deeper comparisson than just the values. So, I'm using now this simple code:

    let isSelected = false;
    selected.forEach((sel) => {
      if (
        sel.a === obj.a
        && sel.b === obj.b
      ) { isSelected = true; }
    });

It works but I wanted to know what better approach to use

ssilas777
  • 9,476
  • 4
  • 43
  • 66
pmiranda
  • 6,162
  • 9
  • 51
  • 114
  • 5
    Does this answer your question? [How to determine if object is in array](https://stackoverflow.com/questions/4587061/how-to-determine-if-object-is-in-array) – Danial Aug 16 '21 at 17:11
  • if your object structure is not supposed to change then you can do check do something like const isSelected = selected.some((item) => JSON.stringify(item) === JSON.stringify(obj)); – Kartik Malik Aug 16 '21 at 17:18
  • Check the difference between Primitive types and Objects https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#javascript_types – Harsh Saini Aug 16 '21 at 17:18

0 Answers0