in Education by
This question already has answers here: How to determine equality for two JavaScript objects? (78 answers) Closed 5 years ago. What is the best way to compare objects in JavaScript? Example: var user1 = {name : "nerd", org: "dev"}; var user2 = {name : "nerd", org: "dev"}; var eq = user1 == user2; alert(eq); // gives false I know that two objects are equal if they refer to the exact same object, but is there a way to check if they have the same attributes' values? The following way works for me, but is it the only possibility? var eq = Object.toJSON(user1) == Object.toJSON(user2); alert(eq); // gives true JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)

1 Answer

0 votes
by
Unfortunately there is no perfect way, unless you use _proto_ recursively and access all non-enumerable properties, but this works in Firefox only. So the best I can do is to guess usage scenarios. 1) Fast and limited. Works when you have simple JSON-style objects without methods and DOM nodes inside: JSON.stringify(obj1) === JSON.stringify(obj2) The ORDER of the properties IS IMPORTANT, so this method will return false for following objects: x = {a: 1, b: 2}; y = {b: 2, a: 1}; 2) Slow and more generic. Compares objects without digging into prototypes, then compares properties' projections recursively, and also compares constructors. This is almost correct algorithm: function deepCompare () { var i, l, leftChain, rightChain; function compare2Objects (x, y) { var p; // remember that NaN === NaN returns false // and isNaN(undefined) returns true if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') { return true; } // Compare primitives and functions. // Check if both arguments link to the same object. // Especially useful on the step where we compare prototypes if (x === y) { return true; } // Works in case when functions are created in constructor. // Comparing dates is a common scenario. Another built-ins? // We can even handle functions passed across iframes if ((typeof x === 'function' && typeof y === 'function') || (x instanceof Date && y instanceof Date) || (x instanceof RegExp && y instanceof RegExp) || (x instanceof String && y instanceof String) || (x instanceof Number && y instanceof Number)) { return x.toString() === y.toString(); } // At last checking prototypes as good as we can if (!(x instanceof Object && y instanceof Object)) { return false; } if (x.isPrototypeOf(y) || y.isPrototypeOf(x)) { return false; } if (x.constructor !== y.constructor) { return false; } if (x.prototype !== y.prototype) { return false; } // Check for infinitive linking loops if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) { return false; } // Quick checking of one object being a subset of another. // todo: cache the structure of arguments[0] for performance for (p in y) { if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) { return false; } else if (typeof y[p] !== typeof x[p]) { return false; } } for (p in x) { if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) { return false; } else if (typeof y[p] !== typeof x[p]) { return false; } switch (typeof (x[p])) { case 'object': case 'function': leftChain.push(x); rightChain.push(y); if (!compare2Objects (x[p], y[p])) { return false; } leftChain.pop(); rightChain.pop(); break; default: if (x[p] !== y[p]) { return false; } break; } } return true; } if (arguments.length < 1) { return true; //Die silently? Don't know how to handle such case, please help... // throw "Need two or more arguments to compare"; } for (i = 1, l = arguments.length; i < l; i++) { leftChain = []; //Todo: this can be cached rightChain = []; if (!compare2Objects(arguments[0], arguments[i])) { return false; } } return true; } Known issues (well, they have very low priority, probably you'll never notice them): objects with different prototype structure but same projection functions may have identical text but refer to different closures Tests: passes tests are from How to determine equality for two JavaScript objects?.

Related questions

0 votes
    This question already has an answer here: Object.assign getters and setters in constructor (1 answer) Closed ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 17, 2022 in Education by JackTerrance
0 votes
    This question already has an answer here: Object.assign getters and setters in constructor (1 answer) Closed ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 17, 2022 in Education by JackTerrance
0 votes
    Which of these method of Object class can generate duplicate copy of the object on which it is called? ... questions and answers pdf, java interview questions for beginners...
asked Oct 25, 2021 in Education by JackTerrance
0 votes
    Here is the example: if(value != ageValue) { ageValue = value; } I mean, if we assign the value ... , JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 24, 2022 in Education by JackTerrance
0 votes
    I ran some test to determine if O(==) for Strings is O(len(string)) or O(1). My tests: ... questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Apr 9, 2022 in Education by JackTerrance
0 votes
    I have a generic method defined like this: public void MyMethod(T myArgument) The first thing I want to ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 24, 2022 in Education by JackTerrance
0 votes
    I have a generic method defined like this: public void MyMethod(T myArgument) The first thing I want to ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 24, 2022 in Education by JackTerrance
0 votes
    I have a generic method defined like this: public void MyMethod(T myArgument) The first thing I want to ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 24, 2022 in Education by JackTerrance
0 votes
    I have a generic method defined like this: public void MyMethod(T myArgument) The first thing I want to ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 24, 2022 in Education by JackTerrance
0 votes
    We have a SQL Server table containing Company Name, Address, and Contact name (among others). We regularly ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Mar 16, 2022 in Education by JackTerrance
0 votes
    As it currently stands, this question is not a good fit for our Q&A format. We expect answers to ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 24, 2022 in Education by JackTerrance
0 votes
    can anybody help me with writing a SOQL query. Using "Date" data type in WHERE statement is easy, ... JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 19, 2022 in Education by JackTerrance
0 votes
    The date stored in my database is 01-01-1900 for field emp_doj(Data Type DATE). But while retrieving ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 19, 2022 in Education by JackTerrance
0 votes
    I used NSNumber class. but methods that can use is different in follow environments. First is a picture in ... Questions for Interview, JavaScript MCQ (Multiple Choice Questions)...
asked Feb 13, 2022 in Education by JackTerrance
0 votes
    Which algorithm uses equality comparison on a key attribute with a primary index to retrieve a single ... Database Interview Questions and Answers for Freshers and Experience...
asked Oct 11, 2021 in Education by JackTerrance
...