Reputation: 4649
Lets say there are two objects but one object has property different from the other. Is there a way to figure out what properties match?
for example:
var objectOne = {
boy: "jack",
girl: "jill"
}
var objectTwo = {
boy: "john",
girl: "mary",
dog: "mo"
}
edit: It should tell me boy
and girl
property name are found in both the objects.
Upvotes: 0
Views: 2872
Reputation: 5729
This isn't better than some solutions here, but I thought I'd share:
function objectHas(obj, predicate) {
return JSON.stringify(obj) === JSON.stringify({ ...obj, ...predicate })
}
Upvotes: 0
Reputation: 38
If you want to find out which keys match given two objects, you could loop through all of the keys of the objects using a for... in
loop. In my function, it will loop through the keys and return an array of all of the matching keys in the two objects.
let objectOne = {
boy: "jack",
girl: "jill"
}
let objectTwo = {
boy: "john",
girl: "mary",
dog: "mo"
}
function matchingKeys (obj1, obj2) {
let matches = [];
let key1, key2;
for (key1 in obj1) {
for (key2 in obj2) {
if ( key1 === key2) {
matches.push(key1);
}
}
}
return matches
}
const result = matchingKeys(objectOne, objectTwo);
console.log(result)
Upvotes: 1
Reputation: 83
Try this on for size:
function compare(obj1, obj2) {
// get the list of keys for the first object
var keys = Object.keys(obj1);
var result = [];
// check all from the keys in the first object
// if it exists in the second object, add it to the result
for (var i = 0; i < keys.length; i++) {
if (keys[i] in obj2) {
result.push([keys[i]])
}
}
return result;
}
Upvotes: 0
Reputation: 4342
Using Object.keys
Object.keys(objectOne).filter(k => Object.hasOwnProperty.call(objectTwo, k))
Upvotes: 2
Reputation: 26022
var in_both = [];
for (var key in objectOne) { // simply iterate over the keys in the first object
if (Object.hasOwnProperty.call(objectTwo, key)) { // and check if the key is in the other object, too
in_both.push(key);
}
}
C.f. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
Now, if you want to test if the values are the same, too, than simply add more code to the condition/body of the inner if
.
Upvotes: 3
Reputation: 42352
You can use Object.keys
and use Array.prototype.reduce
to loop through once and list out the common keys - see demo below:
var objectOne={boy:"jack",girl:"jill"};
var objectTwo={boy:"john",girl:"mary",dog:"mo"};
var result = Object.keys(objectOne).reduce(function(p,c){
if(c in objectTwo)
p.push(c);
return p;
},[]);
console.log(result);
Upvotes: 1