Skip to content

JavaScript compares object key values | Code

  • by

First, get keys from the object as an array using the object keys() method and then compare object key values to the given key in the loop in JavaScript.

JavaScript compares object key values

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
   var myString = "Item1";

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

  var keys = Object.keys(jsObject); 

  keys.forEach(function(key) { 
    console.log(key, key == myString)
  });
</script>

</body>
</html>

Output:

JavaScript compares object key values

Direct Comparison: If you want to compare the values of two keys in an object, you can access them directly using dot notation or bracket notation and then compare them using any comparison operator.

let obj = { key1: 'value1', key2: 'value2' };

if (obj.key1 === obj.key2) {
    console.log('Values are equal');
} else {
    console.log('Values are not equal');
}

Iterating through Objects: If you have multiple objects or want to dynamically compare keys, you can iterate through the objects and compare their key values.

let obj1 = { key1: 'value1', key2: 'value2' };
let obj2 = { key1: 'value1', key2: 'value2' };

function compareObjects(obj1, obj2) {
    for (let key in obj1) {
        if (obj1.hasOwnProperty(key) && obj2.hasOwnProperty(key)) {
            if (obj1[key] === obj2[key]) {
                console.log(`Values of ${key} are equal`);
            } else {
                console.log(`Values of ${key} are not equal`);
            }
        }
    }
}

compareObjects(obj1, obj2);

This function iterates through all keys of obj1 and checks if obj2 also has that key. Then, it compares the values of the corresponding keys.

Do comment if you have any doubts or suggestions on this Js object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading