Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I test if two javascript objects are similar?
    text
    copied!<p>In Javascript (no jquery or other frameworks please) I want to test if 2 (or more) objects are the same type of object.</p> <p>Here are some sample objects:</p> <pre><code>function Person (firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } function Animal (name, type, age) { this.name = name; this.type = type; this.age = age; } var family = {}; family.father = new Person ('John', 'Doyle', 33); family.mother = new Person ('Susan', 'Doyle', 32); family.pet = new Animal ('Jodie', 'Cat', 2); </code></pre> <p>Given the above objects, I want a generic way to test if family.father, family.mother, and family.pet are from the same "type" of object. Can I test for the difference between Person and Animal in a generic way. Something like:</p> <pre><code>if ( sourceObject(family.father) === sourceOjbect(family.mother) ) { alert('father and mother are the same type'); } else { alert('father and mother are not from the same object... we could have problems.'); } if (sourceObject(family.pet) !== sourceObject(family.father)) { alert('the pet is a different type than the father'); } else { alert('Perhaps it should be a child instead of a pet?'); } </code></pre> <p>or perhaps something like this:</p> <pre><code>if (isSameObject(family.pet, family.father)) { alert('Perhaps it should be a child instead of a pet?'); } else { alert('Father and pet are different.'); } </code></pre> <p>There is no "sourceObject" function, but I'm trying to find out if there IS something that does this or someone has found a quick way to do that comparison.</p> <p>Note I am not looking to compare the data in the objects, I am looking to compare the type of Objects involved in the comparison. I need to do this without knowing the exact make up of the components involved. For example, in the above code I could test for a "type" property, but that requires foreknowledge of the objects. I am trying to write a generic function that will not necessarily know anything about the objects passed to it other than the objects them selves.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload