0

I have two objects and would like to return true if both of them have one key-value pair that is the same, for example.

let obj1 = {
  toyota: 'yellow'
  honda: 'silver'
  mazda: 'black'
}

let obj2 = {
  nissan: 'black',
  bmw: 'yellow',
  honda: 'silver',
}

const MatchKey = function (obj1, obj2, key) {
 let obj1 = JSON.stringify(obj1)
 let obj2 = JSON.stringify(obj2)
}

since both objects have the same key/value pair (honda: 'silver') the function would return true.

Striped
  • 2,544
  • 3
  • 25
  • 31
  • `obj1.honda === obj2.honda`? – VLAZ Nov 09 '20 at 07:17
  • Does this answer your question? [How to iterate over a JavaScript object?](https://stackoverflow.com/questions/14379274/how-to-iterate-over-a-javascript-object) – Cid Nov 09 '20 at 07:19
  • Do you want to check if there is **exactly one** key/value pair that is the same or **at least one**? – lacrit Nov 09 '20 at 08:41

2 Answers2

0

Object[key] will return the value of the key on object.

So you can compare values simply by getting the value of key on object directly.

let obj1 = {
  toyota: 'yellow',
  honda: 'silver',
  mazda: 'black'
};

let obj2 = {
  nissan: 'black',
  bmw: 'yellow',
  honda: 'silver',
};

const MatchKey = function (obj1, obj2, key) {
  return obj1[key] === obj2[key];
};

console.log(MatchKey(obj1, obj2, 'honda'));
Derek Wang
  • 10,098
  • 4
  • 18
  • 39
0

Short functional implementation. It will compare all entries from one with another and vice versa.

    let o1 = {
        toyota: 'yellow',
        honda: 'silver',
        mazda: 'black'
    }

    let o2 = {
        nissan: 'black',
        bmw: 'yellow',
        honda: 'silver'
    }
            
    const isObject = (x) => typeof x === 'object';

    const foundDuplicates = (x, y) => 
      !(x && y && isObject(x) && isObject(y)) ? 
       x === y : Object.keys(x).some(key => foundDuplicates(x[key], y[key]));


    console.log(foundDuplicates(o1, o2))

This does, however, return true if there is at least one key/value pair that is the same.

lacrit
  • 115
  • 5