Comparing values between two JSON objects in Angular 8: A guide

I need to compare the values of two objects, obj1 and obj2, by ignoring keys that are missing in either object. If all key-value pairs are equal, return false; otherwise, return true.

For example: If 'id' is present in obj1 but not in obj2, it should be ignored during comparison.

Is there a more efficient way to compare values between two objects with minimal code?

Below is my attempted code snippet

compareResponseAndFormValue(){   
    const result = JSON.stringify(this.obj1) === JSON.stringify(this.obj2);
    console.log(result,"result")
    
  }

Expected output:

The value of the 'bankHoliday' column differs between obj1 and obj2, so the comparison should return true.

Sample response:

const obj1 = {
    "id": "",
    "uom": "OOOUnits",
    "classifiedHours": 720,    
    "entryType": "Monthly",
    "entryDetails": {
        "month": "April",
        "year": 2024
    },
    "dataSource": "MDCS",
    "availableTime": {
        "bankHoliday": "8"
    },
    "valueOperatingTime": {
        "breakDownTime": null
    },
    "operatingTime": {
        "maintenanceTime": 0
    },
    "loadingTime": {
        "nominalSpeed": "130"
    },
    "oeeCalculations": {
        "others": {
            "totalTime": 720
        }
    }
}

const obj2 = 
{
   
    "lineId": "E_A571_D",
    "classifiedHours": null,
    "entryDetails": {
        "month": "April",
        "year": 2024
    },
    "availableTime": {
        "bankHoliday": "6.05"
    },
    "valueOperatingTime": {
        "breakDownTime": null
    },
    "operatingTime": {
        "maintenanceTime": 0
    },
    "loadingTime": {
        "nominalSpeed": "130"
    },
    "oeeCalculations": {
        "others": {
            "totalTime": 720
        }
    },
    "uom": "OOOUnits"  
}

Answer №1

Yes, I have a unique function that can help you compare two objects by ignoring keys that are not present in both objects. It will return true if there is any difference between the values of the objects.

 function compareObjects(obj1, obj2) {
    for (let key in obj1) {
      if (obj2.hasOwnProperty(key)) {
        if (typeof obj1[key] === 'object' && obj1[key] !== null && obj2[key] !== null) {
          if (compareObjects(obj1[key], obj2[key])) {
            return true;
          }
        } else if (obj1[key] !== obj2[key]) {
          return true;
        }
      }
    }
    return false;
  }
  1. The function goes through each key in obj1 and checks if it exists in both objects.
  2. If the key exists in both objects, it then compares the values. If the values are objects, it recursively calls the function to compare nested objects.
  3. If the values are not objects or are null, it directly compares them.
  • If any pair of values is different, the function returns true.
  • If all keys are checked without finding differences, it returns false which means the objects are equal, ignoring keys not present in both objects.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to display each value from the array arr, containing strings, on separate lines?

Can you complete the function below to display each value in the array 'arr' on separate lines? <!DOCTYPE html> <html> <head> <title> ...

Interactive Communication: PHP and JQuery Messaging Platform

I am developing a social networking platform and I am looking to integrate a chat feature. Currently, I have a home.php page that displays a list of friends. The friends list is loaded dynamically using jQuery and PHP, like this: function LoadList() { ...

How can the value attribute be obtained from the click class?

$(document).on('click','.edit', function(){ var appid = $(this).getAttribute('value'); I am trying to figure out how to save the value of the "value" attribute for an image with the edit class. Can anyone help me with thi ...

Creating intricate JavaScript objects for JSON API integration can be accomplished by following these steps:

Here is a sample JSON structure used for querying an API: "order_items": [ { "menu_item_id": "VD1PIEBIIG", "menu_item_name": "Create Your Own", "modifiers": [ { "modifier_id ...

A guide on traversing through nested HTML divs using jQuery

I am facing an issue with nested HTML div elements on my website. The data is being fetched from a JSON file and stored in a variable. For example, the 'obj' variable contains an array of objects with properties such as Name, Progress, Descripti ...

Is there a way to automatically collapse all the collapsible elements within the accordion when closing it?

I came across a similar topic on Stack Overflow about closing all children accordions when the parent accordion is closed, which seems to address my issue. Currently, I am using Bootstrap 4 and struggling to modify the code from the other topic to ensure ...

Experience the power of CanJS Observable data objects with the added feature of

When working with canJS Observable, I encountered an issue where I cannot use dots in object keys because canJS interprets them as nesting. For example, if I try to create a new observable like this: var obs = new can.Observe( { "div.test-class": { "color ...

Navigating a local and server environment with relative paths in a web server's multiple sites

My ASP.NET website is published to a web server with multiple sites, such as www.example.com/SiteA or www.example.com/SiteB. Before publishing, I test the site locally at localhost:12345. When referencing an image path like /Images/exampleImage.gif, it wo ...

Using the useStaticQuery hook outside of a function component is not allowed and will result in an invalid hook call error. Remember to only call

I am currently facing an issue while trying to retrieve values using useStaticQuery from my gatsby-config.js file. Below are snippets of my code. Does anyone have any suggestions on how to resolve this problem? Thank you in advance. Repository: https: ...

Send the innerHTML content to the data layer in Tag Manager

As a newcomer to HTML and CSS, I apologize if this question has already been asked. I am currently working on implementing tags for a new website that keeps track of the number of times sections are viewed on a page. The section names are stored in a var ...

removing the mapStateToProps function will result in an undefined value

I am new to React and I'm in the process of converting a class component to functional components using hooks. I need some guidance on safely removing 'mapStateToProps' without encountering undefined errors. I have two pages, A.js and B.js. ...

Strange compilation issue "Syntax error: Unable to access 'map' property of null" occurs when map function is not utilized

I recently developed a custom useToggle hook that does not rely on the .map() method: import { useState } from "react"; export const useToggle = ( initialValue: boolean = false ): [boolean, () => void] => { const [value, setValue] = us ...

Struggling to retrieve a particular user using ExpressJs due to an error

Looking to retrieve a specific user in ExpressJS from a JSON file. Encountering this error message: UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client This is the snippet of code being u ...

jquery module for retrieving and updating messages

I want to develop a custom plugin that can be utilized in a manner similar to the following example. This isn't exactly how I plan to use it, but it serves as the initial test for me to fully grasp its functionality. HTML: <div id="myDiv">< ...

Listening for select elements that have remained unchanged

My current situation involves a select box with predetermined options. One of these options is preselected when the page loads: <select name="select" class="js-choice-select"> <option value="option-1">Option 1</option> <option ...

Utilizing v-for in Vue with TypeScript to generate multiple checkboxes

My goal was to capture the values of checkboxes and store them in an array using v-model. However, I encountered an issue where the first time I toggle a checkbox, it doesn't register. Only after checking a second box and hitting submit does the secon ...

Instead of leaving an Enum value as undefined, using a NONE value provides a more explicit

I've noticed this pattern in code a few times and it's got me thinking. When you check for undefined in a typescript enum, it can lead to unexpected behavior like the example below. enum DoSomething { VALUE1, VALUE2, VALUE3, } f ...

Getting rid of background color in a tooltip using Material UI

I'm currently tackling an issue with Material UI's tooltip. I can't seem to find a way to make the background of the tooltip completely transparent. By default, it displays with a grey background and white text. Changing the background color ...

Utilizing Ternary Operators with User Input

In my latest project, I am developing a cutting-edge app that converts text to sound, utilizing input text from react-native-elements along with ternary operators. My main challenge now is figuring out how to validate whether the text input box is empty ...

When attempting to retrieve JSON data for the second time, AJAX fails to fetch the information

After successfully sending an Ajax request to a php file and receiving a JSON array of the submitted data, I encountered an error on the second attempt. The error message reads: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSO ...