0

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.

3
  • Your example doesn't show much. What do you mean? Commented Dec 14, 2016 at 2:35
  • 1
    So you want a list of property names that are in both objects, without regard for what their values are? Shall we assume no object nesting? Commented Dec 14, 2016 at 3:04
  • @ nnnnnn . Yes Exactly. Commented Dec 14, 2016 at 3:30

6 Answers 6

3
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.

Sign up to request clarification or add additional context in comments.

3 Comments

Why not objectTwo.hasOwnProperty(key)? How does .call() help? (Interesting choice to link to the German documentation.)
@nnnnnn, objectTwo could have its own item hasOwnProperty. Not using .call is an easy attack vector, though it's unlikely to cause more than a DOS. Oops, did not notice that I linked the wrong language. You may simply edit the question next time.
Fair enough. I guess in my own code I'm generally dealing with objects I've created myself, where there would definitely not be an own hasOwnProperty. But your way works for any object.
2

Using Object.keys

Object.keys(objectOne).filter(k => Object.hasOwnProperty.call(objectTwo, k))

4 Comments

Your code solves the question in quadratic time when linear time would do. Do not do that in production!
Here is linear :P
You should use hasOwnProperty, because null and undefined might be valid values.
You're welcome. Your one-line solution is the prettiest, IMO. No needless (explicit) loops.
1

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

Comments

1

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)

7 Comments

@Kay - I find this easy enough to read, other than the weird mix of var, let, and undeclared-and-therefore-global variables.
@Kay Thank you for the feedback, you're right, it can be done linear time. I tried to improve the readability, but I keep the spirit of my original solution.
@nnnnn Thank you for the feedback, I made my variables consistent. You da best 🙏
The key1 and key2 variables are still global, and - more importantly - your code doesn't actually run...
@nnnnn Fixed my answer - thanks again for the heads up.
|
0

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;
}

Comments

0

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 })
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.