Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check that two objects have the same set of property names?

I am using node, mocha, and chai for my application. I want to test that my returned results data property is the same "type of object" as one of my model objects (Very similar to chai's instance). I just want to confirm that the two objects have the same sets of property names. I am specifically not interested in the actual values of the properties.

Let's say I have the model Person like below. I want to check that my results.data has all the same properties as the expected model does. So in this case, Person which has a firstName and lastName.

So if results.data.lastName and results.data.firstName both exist, then it should return true. If either one doesn't exist, it should return false. A bonus would be if results.data has any additional properties like results.data.surname, then it would return false because surname doesn't exist in Person.

This model

function Person(data) {   var self = this;   self.firstName = "unknown";   self.lastName = "unknown";    if (typeof data != "undefined") {      self.firstName = data.firstName;      self.lastName = data.lastName;   } } 
like image 458
dan27 Avatar asked Jan 16 '13 21:01

dan27


People also ask

How do you check if two objects have the same values?

If the two objects have the same values, equals() will return true . In the second comparison, equals() checks to see whether the passed object is null, or if it's typed as a different class. If it's a different class then the objects are not equal.

Can we have two properties with the same name inside an object?

You cannot. Property keys are unique. Follow TravisJ 's advice. You might want to look up the term 'multimap', too.

How do you check if an object has properties?

The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.


1 Answers

You can serialize simple data to check for equality:

data1 = {firstName: 'John', lastName: 'Smith'}; data2 = {firstName: 'Jane', lastName: 'Smith'}; JSON.stringify(data1) === JSON.stringify(data2) 

This will give you something like

'{firstName:"John",lastName:"Smith"}' === '{firstName:"Jane",lastName:"Smith"}' 

As a function...

function compare(a, b) {   return JSON.stringify(a) === JSON.stringify(b); } compare(data1, data2); 

EDIT

If you're using chai like you say, check out http://chaijs.com/api/bdd/#equal-section

EDIT 2

If you just want to check keys...

function compareKeys(a, b) {   var aKeys = Object.keys(a).sort();   var bKeys = Object.keys(b).sort();   return JSON.stringify(aKeys) === JSON.stringify(bKeys); } 

should do it.

like image 196
Casey Foster Avatar answered Oct 05 '22 23:10

Casey Foster