1

I'm trying to figure out how to loop over two objects at the same time so that I can compare their properties. What I tried was something like

for ((prop1, prop2) in (obj1, obj2) {
    console.log(prop1 == prop2)
}

which definitely didn't work. How do I do this in js?

3 Answers 3

3

In a basic way, would be it:

var obj1 = {
    prop1: 'prop1',
    prop2: 'prop2'
};

var obj2 = {
    prop1: 'prop1',
    prop2: 'prop2',
    prop3: 'prop3'
};

for (var prop in obj1) {
    console.log(prop, obj1[prop] == obj2[prop]);
}
Sign up to request clarification or add additional context in comments.

Comments

3

You can use Object.keys() and Object.assign() function.

Object.keys(Object.assign({}, obj1, obj2)).forEach(function(key) {
    var prop1 = obj1[key];
    var prop2 = obj2[key];
    console.log(prop1 == prop2);
});

Note: check for browser compatibility of Object.assign() function. Currently it is not supported by IE.

Comments

0

You can't, you need to do it in 2 for.

for (var prop1 in obj1) {
  for(var prop2 in obj2)
    console.log(prop1 == prop2);
}

You could try that too, without 2 loops:

for (var prop1 in obj1) {
  console.log(obj2[prop1] === undefined);
}

2 Comments

Why am I checking if it's undefined?
@AlanH: if obj2[prop1] is undefined, it means that obj2 doesn't have prop1 attribute.

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.