How do I check if two objects have the same properties?

Supposed I have two objects (the code is below), how do I check if both objects have the same properties?
eg:

obj_1 ={
	Name : 'Paul Hackman',
	Degree : 'Marine Science',
	Employed : true
};

obj_2 ={
	Name : 'Tom Peterson',
	Degree : 'Mechanical Engineering',
	Employed : false
};

// I tried with the below technique but it didn't work.

const value_1 = Object.keys(obj_1);
const value_2 = Object.keys(obj_2);

if ( value_1 === value_2){
    console.log('both objects have the same properties');
 }else{
  console.log('the properties are not the same in the two given objects');
}

Even though I assigned both object with the same properties, but the code in the ‘else’ block was the output.
Please I need help

Hello! Because Object.keys(obj_1) returns an array, you can’t simply use if (array1 === array2). You’ll have to use some other way to check if all of the elements in the arrays value_1 and value_2 are the same.

Hint

Consider using dome nested loops to check this.

The basic syntax of a nested loop"

for (let i = 0; i > condition; i++) {
  for (let j = 0; j > condition; j++) {
     //code
  }
}

I hope this helps!

3 Likes
for (let i =0; i < value_1.length; i++){
	for(let j = 0; j < value_2.length; j++){
		if(value_1[ i ] === value_2[ j ]){
			console.log('both objects have the same properties ' + value_2[ j ]);
		}
	}
}

Hello @codeneutrino , I did exactly what you said and it worked. Though, the code runs by comparing the current element from the outer loop array ( value_1[ i] ) to each element in the inner array ( value_2[ j ]) as opposed to just logging a simple message like “both objects have the same properties” in the case if “object_1” ’ s properties are just the same as “object_2” 's properties, and logs other simple message if it isn’t.
However, I think this technique works the same, just that in the case where there are many properties in object_1 which exist in object_2, there would be more messages logged to the console.
Thanks a lot.

If you wanted only one message logged to the console, you could do something like have a counter variable incremented every time the two arrays have the same value. Then check whether the counter variable matches the length of one of the arrays-and then you could only log one message.

2 Likes

Thanks a lot. You’ve really solved what I have been battling with for the past few days.
I appreciate it a lot.

1 Like