简体   繁体   中英

Javascript Comparing if Two objects share one same key/value pair

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.

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'));

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM