Solved

Comparing Objects in JavaScript

Posted on 2009-07-07
8
1,113 Views
Last Modified: 2012-08-13
Hi Guys,

Does anyone have a good method that can returns true if all values in one object match that in another object? (it needs to support recursion too)

Ex:
var o1 = {
  item1:123
  item2: {
    item3: 456
  }
}
var o2 = {
  item1:123
  item2: {
    item3: 456
  }
}
var o3 = {
  item1:123
  item2: {
    item3: 'ABC'
  }
}

So when comparing o1 to o2 the method would eval to true, comparing o1 to o3 would eval to false.

Cheers,
Dan
0
Comment
Question by:dancablam
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 2
8 Comments
 
LVL 41

Expert Comment

by:HonorGod
ID: 24798729
That might be difficult.  Consider the scenario where the object contains a "this" reference.
The eval would only be able to return true if the objects being compared refer to a single object.
0
 
LVL 41

Expert Comment

by:HonorGod
ID: 24798759
A simple test to see if two variables reference the same object would be to use the === operator.


function same( a, b ) {
  return a === b;
}

Open in new window

0
 
LVL 3

Author Comment

by:dancablam
ID: 24798823
The objects will only contain data - not methods. Also they won't be referencing the same object so the === won't work. I simply need a method to walk recursively down an object and see if all the property/value combinations match.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 3

Expert Comment

by:laneway
ID: 24798892
This will work for objects that both have the same values:
function compareObj(obj1,obj2) {
    // if obj1 and obj2 are not both objects, return simple comparison
    if (typeof obj1 != 'object' || typeof obj2 != 'object') { return (obj1==obj2); }
    // compare indexes in obj1 with those in obj2
    for (index in obj1) {
      var item1 = obj1[index];
      var item2 = obj2[index];
      if (typeof item1 == 'object') if (!compareObj(item1,item2)) return false;
      if (typeof item1 != 'object') if (item1!=item2) return false;
    }
    // if we got this far, the are the same
    return true;
} 
 
// demo
var o1 = { item1:123, item2: { item3: 456 } };
var o2 = { item1:123, item2: { item3: 456 } };
var o3 = { item1:123, item2: { item3: 'ABC' } };
alert(compareObj(o1,o2));
alert(compareObj(o1,o3));

Open in new window

0
 
LVL 3

Expert Comment

by:laneway
ID: 24798913
Clarification. The above code will work for objects that both have the same properties. Example:
// comparing these two will work
var o1 = { item1:'abc' }
var o2 = { item1:'def' }
// but comparing these two won't always work properly
var o1 = { item1:'abc' }
var o2 = { item1:'def',item2:'xyz' }

Open in new window

0
 
LVL 41

Expert Comment

by:HonorGod
ID: 24798981
Something like this perhaps?
<html>
<body>
 
<script type="text/javascript">
var o1 = {
  item1 : 123,
  item4 : 'Hi',
  item2 : { item3 : 456 }
}
var o2 = {
  item1 : 123,
  item4 : 'hi',
  item2 : { item3 : 456 }
}
var o3 = {
  item1 : 123,
  item4 : 'Hi',
  item2 : { item3 : 'ABC' }
}
 
function oCompare( o1, o2 ) {
  var result = false;
  if ( typeof( o1 ) == typeof( o2 ) ) {
    if ( typeof( o1 ) == 'object' ) {
      if ( o1 === o2 ) {
        return true;
      } else {
        for ( p in o1 ) {
          if ( p in o2 ) {
            var T = typeof( o1[ p ] );
            if ( T == typeof( o2[ p ] ) ) {
              switch ( T ) {
                case 'boolean' : if ( o1[ p ] != o2[ p ] ) return false;
                  break;
                case 'number' : if ( o1[ p ] != o2[ p ] ) return false;
                  break;
                case 'function' : if ( o1[ p ] !== o2[ p ] ) return false;
                  break;
                case 'string' : if ( o1[ p ] != o2[ p ] ) return false;
                  break;
                case 'object' : if ( !oCompare( o1[ p ], o2[ p ] ) ) return false;
                  break;
                default:
                  alert( 'p: ' + p + ' typeof: ' + T );
              }
            } else {
              return false;
            }
          } else {
            return false;
          }
        }
      }
    }
  }
  return result;
}
 
document.write( oCompare( o1, o3 ) );
 
</script>
 
</body>
</html>

Open in new window

0
 
LVL 41

Accepted Solution

by:
HonorGod earned 500 total points
ID: 24799040
nope, not quite...

We also have to check that all properties in object2 exist and are the same as found in object1...
<html>
<body>
 
<script type="text/javascript">
var o1 = {
  item1 : 123,
  item4 : 'Hi',
  item2 : { item3 : 456 }
}
var o2 = {
  item1 : 123,
  item4 : 'Hi',
//item5 : true,
  item2 : { item3 : 456 }
}
var o3 = {
  item1 : 123,
  item4 : 'Hi',
  item2 : { item3 : 'ABC' }
}
 
function oCompare( o1, o2 ) {
  if ( typeof( o1 ) == typeof( o2 ) ) {
    if ( typeof( o1 ) == 'object' ) {
      if ( o1 === o2 ) {
        return true;
      } else {
        for ( p in o1 ) {
          if ( p in o2 ) {
            var T = typeof( o1[ p ] );
//          alert( p + ' ' + o1[ p ] + ' ' + o2[ p ] );
            if ( T == typeof( o2[ p ] ) ) {
              switch ( T ) {
                case 'boolean' : if ( o1[ p ] != o2[ p ] ) return false;
                  break;
                case 'number' : if ( o1[ p ] != o2[ p ] ) return false;
                  break;
                case 'function' : if ( o1[ p ] !== o2[ p ] ) return false;
                  break;
                case 'string' : if ( o1[ p ] != o2[ p ] ) return false;
                  break;
                case 'object' : if ( !oCompare( o1[ p ], o2[ p ] ) ) return false;
                  break;
                default:
//                alert( 'p: ' + p + ' typeof: ' + T );
              }
            } else {
              return false;
            }
          } else {
            return false;
          }
        }
      }
    }
  }
  return true;
}
 
document.write( oCompare( o1, o2 ) && oCompare( o2, o1 ) );
 
</script>
 
</body>
</html>

Open in new window

0
 
LVL 41

Expert Comment

by:HonorGod
ID: 24842512
Thanks for accepting my solution.

I'm sorry that you didn't feel that it was worthy of an A.

Good luck & have a great day.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
JavaScript code not working 3 33
Triple line in an alert message 4 24
disable and enable textboxes in dataTable 7 30
setInterval() calls function twice in one interval 2 36
Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question