How to Compare two Objects in JavaScript

How to Compare two Objects in Javascript

Introduction

Do you know how to compare two objects in javascript? If you don’t know how to do it, this article is for you. Most people know how to create objects in JS, but don’t know how to compare two objects. Let me tell you to step by step with examples.

To compare two objects in Javascript, we need to use the “===” triple-equals sign.

Example:

var str= "Item1";

var jsObject = 
{
    Item1:
    {
        "red": "apple",
        "orange": "oranges",
    },
    Item2:
    {
        "yellow": "bannana",
        "green": "pears"
    }
};

var keys = Object.keys(jsObject); //get keys from object as an array

keys.forEach(function(key) { //loop through keys array
  document.write(key, key === str)
});

Output:

 how to compare two objects in javascript

Leave a Reply