-1

I am trying to add a set on unique key value pairs however when I check to see if that object is inside the object it is saying it isn't. What's the best way to see if an object already contains a different object?

const obj = {
  1: {row: 1, col: 1},
  2: {row: 2, col:2 }
}

const test = { row:1, col: 1 }


Object.values(obj).indexOf(test) // returns -1
Fabrizio
  • 7,603
  • 6
  • 44
  • 104
  • 2
    Possible duplicate of [How to determine equality for two JavaScript objects?](https://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects) – gaetanoM Mar 25 '18 at 18:16

3 Answers3

0

Objects with identical values are never === unless they both stem from the same object reference. When you test whether an object is === to another, it's basically checking whether both variables point to the same location in memory.

Here, you've created one object 1: {row: 1, col: 1}, and then you create another in test. They're different, so testing if obj includes test will fail.

Test inside of a findIndex function instead:

const obj = {
  1: {row: 1, col: 1},
  2: {row: 2, col:2 }
}

console.log(Object.values(obj).findIndex(testObj => testObj.row === 1 && testObj.col === 1))
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

Here's a more versatile solution. You could compare the object with JSON.stringify. Then you don't have to compare each value of the object.

const obj = {
  1: {row: 1, col: 1},
  2: {row: 2, col:2 }
}

const test = { row:1, col: 1 }

var count = Object.keys(obj).map(key => obj[key]).filter(value => JSON.stringify(value) === JSON.stringify(test)).length;


console.log(count);
David Ibl
  • 901
  • 5
  • 13
0

It fails because, although the two objects contain the same data, they are not the exact same two object "instances" in memory (i.e. two people named "Scott" are not the exact same one "Scott").

If you tested against an actual object in memory, you'd get a better result:

const obj = {
  1: {row: 1, col: 1},
  2: {row: 2, col:2 }
}

const test = obj["1"];
console.log(Object.values(obj).indexOf(test)); 

So, the thing to do here is to convert each object to a string and then look for the string:

const obj = {
  1: {row: 1, col: 1},
  2: {row: 2, col:2 }
}

let sObj = JSON.stringify(obj); // Convert object to be tested against into a JSON string

function testKeys(key){
  Object.keys(obj).forEach(function(o){
    if(JSON.stringify(obj[o]).indexOf(key) > -1){
      console.log("Match found at key: " + o); 
    } else {
      console.log("No match found at key " + o);
    }
  });
  console.log("-".repeat(25));  
}

testKeys(JSON.stringify({row: 1, col: 1}));
testKeys(JSON.stringify({row: 2, col:2 }));
testKeys(JSON.stringify({row: 2, col: 3}));
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71