determine variances between two Java script objects

I need help with comparing two JavaScript objects to find the differences. The code I am using in the function is not giving me the desired output.

function compare() {
  var Json1 = [
    { name: "ABC", value: "5" },
    { name: "DEF", value: "85712264" },
  ];
  var Json2 = [
    { name: "DEF", value: "85712264" },
    { name: "ABC", value: "3" },
  ];

  var obj1Keys = Object.keys(Json1);
  var obj1Values = Object.values(Json1);
  var obj2Keys = Object.keys(Json2);
  var obj2Values = Object.values(Json2);
  console.log(obj1Keys);
  console.log(obj1Values);

  for (let i = 0; i < obj1Keys.length; i++) {
    for (let j = 0; j < obj2Keys.length; j++) {
      if (obj1Keys[i] === obj2Keys[j]) {
        if (obj1Values[i] !== obj2Values[j]) {
          console.log(obj1Keys[i]);
          console.log(obj1Values[i]);
        }
      }
    }
  }
}

I am attempting to compare the 'name' and 'value' from Json1 with Json2. If a matching 'name' is found, then I want to compare the 'value' for that 'name'. If there is a difference in the 'value', I would like to print the 'name' and 'value' pair from Json1.

Expected result: ABC, 5

Thank you for your assistance!

Answer №1

If you're looking to compare the attributes and values of two objects in JavaScript, using the .forEach() method is a great approach. Here's an example of how you can achieve that, with a focus on the use of object destructuring assignment in the first loop.

var Json1 = [
  { name: "ABC", value: "5" },
  { name: "DEF", value: "85712264" },
];
var Json2 = [
  { name: "DEF", value: "85712264" },
  { name: "ABC", value: "3" },
];

var obj1Keys = Object.keys(Json1);
var obj1Values = Object.values(Json1);
var obj2Keys = Object.keys(Json2);
var obj2Values = Object.values(Json2);

Json1.forEach(({name, value}) => {
   Json2.forEach((elem) => {
    if( name === elem.name && value !== elem.value) {
      console.log(name, value);
    }
  })
});

Answer №2

Are you looking for a solution?

let data1 = [{ "name": "ABC", "value": "5" }, { "name": "DEF", "value": "85712264" }];
    let data2 = [{ "name": "DEF", "value": "85712264" }, { "name": "ABC", "value": "3" }];

    for (let i = 0; i < data1.length; i++) {
      const { name, value } = data1[i];
      for (let j = 0; j < data2.length; j++) {
        const jsonData2 = data2[j];
        if (name === jsonData2.name ) {
          console.log(name, value);
        }
      }
    }

Answer №3

function findAndCompareValues(){
         var JsonData1 = [{
            label: "ABC",
            amount: "5"
        },
        {
            label: "DEF",
            amount: "85712264"
        },
    ];
    var JsonData2 = [{
            label: "DEF",
            amount: "85712264"
        },
        {
            label: "ABC",
            amount: "3"
        },
];

    // As both JsonData1 and JsonData2 are arrays, Object.keys not needed

    JsonData1.forEach((item, index) => {
        // Find corresponding item in JsonData2
        let correspondingItem = JsonData2.find(obj => obj.label === item.label) || {}

        // Compare values
        if (correspondingItem.amount && item.amount !== correspondingItem.amount) {
            console.log(item.label, item.amount)
        }

    })
}

findAndCompareValues()

Answer №4

Here's a slight modification to the code snippet provided:

const jsonData1 = [  
{ key: "name", value: "John" },
  { key: "age", value: "25" },
];
const jsonData2 = [
  { key: "age", value: "30" },
  { key: "name", value: "Jane" },
];
const dataMap = new Map();
Object.keys(jsonData1).forEach(k => dataMap.set(jsonData1[k].key, jsonData1[k].value));
Object.keys(jsonData2).forEach(k => {
    if(dataMap.has(jsonData2[k].key) && dataMap.get(jsonData2[k].key) !== jsonData2[k].value)
        console.log(jsonData2[k].key, dataMap.get(jsonData2[k].key));
});

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

Converting a JSON object to a JSON array can sometimes be challenging during JSON parsing

I'm attempting to convert a JSON String into an array by using the code snippet below: try { String holder = getJSONString(getApplicationContext()); JSONArray JSONARR= new JSONArray(holder); List<datatemp> dataList = new ArrayList& ...

Creating a SAS URL for Azure Blob storage in Node.js using the generateBlobSASQueryParameters method from the @azure/storage-blob module

Hello, I am working with an Azure storage account where I upload and create a SAS URL to download images. Below is the code snippet that I have used: const { BlobServiceClient, StorageSharedKeyCredential, BlobSASPermissions, generateBlobSASQueryPar ...

Retrieve data from Postgres by searching for multiple array elements within each row and returning them as JSON

I need to extract all subscriptions with an interval of "1 WEEK" from the 'data' column provided below: [ { "id": "tran_6ac25129951962e99f28fa488993", "amount": 1200, "client": { "id": "client_622bdf4cce2351f28243", "su ...

Form Validation in JavaScript Continues to Submit Form Even When 'False' is Detected

Here is the issue at hand - I am restricted to using older browsers (IE8 and FF8) by corporate policy. Despite my research indicating otherwise, it seems like this might be the root cause of my troubles. My current setup includes PHP 5.5.12 on Apache 2.4. ...

What are the steps to utilize chrome.tabs.onUpdated.addListener?

I am currently working on a Chrome extension where I need to display an alert() showing the page URL whenever the user switches tabs or enters a new URL in a tab. However, my current implementation is not functioning as expected: chrome.tabs.onUpdated.ad ...

Tips for fixing the error "Unhandled error: state.set is not a function"

My code is utilizing immutable.js in the reducer, but I keep encountering an error stating 'state.set is not a function'. Interestingly, when I modify the code to exclude immutable, the error disappears. import React from 'react'; impo ...

sending a pair of variables via jQuery and AJAX

Having difficulty posting two variables using ajax and jquery when a button on a confirm window is pressed. Each variable can be displayed separately, but not both at the same time. UPDATE - Issue resolved. I overlooked including a necessary file. My mist ...

The pagination in Laravel Vue is causing a validation error due to an invalid prop type check failing

Recently, I delved into working with Nuxt.js and decided to install the Laravel-Vue-Pagination plugin. However, I encountered an error message in my console system that reads: [Vue warn]: Invalid prop: type check failed for prop "data". Expected Object, ...

Sending a JSON response back to an AJAX request triggers a file download that includes the response

When submitting a form using jQuery ajax, the server returns a json response. However, rather than parsing the json result, the browser prompts me to download the json response. I've encountered this problem in the past when I forgot to return false ...

Using Node.js to insert a new element into a JSON array

I am working with a JSON array [{id:1,data:"test1"},{id:2,data:"test2"}] My goal is to add a new element to each object in the array based on the value of the "data" field. For example, if the data value is "test1", ...

Transform an array of dictionaries into JSON format

My API requires JSON data to be in the following format: { "user_contacts" : [ { "friend_list" : "+928885555512", "user_id" : "1" }, { "friend_list" : "+925555648583", "user_id" : "1" }, { "friend_list" ...

Minimize the amount of external asynchronous calls made by the client

In my application, the client initiates multiple asynchronous JavaScript requests to third party servers. The issue I'm encountering is that when the client responds to these requests, the site becomes inactive for a brief period of time. This inactiv ...

Tips on saving two variables in a 2D array and sending it through an AJAX request

I am looking to store pairs of data in a 2D array like this. var items = [ [1, 2], [3, 4], [5, 6] ]; I have already attempted the following: let ot_array = []; $(document).on('click', '.overtime_send', function() { $(&apos ...

Utilizing Mongoose.js to nest a find() query within another find() query

Can I perform a nested search on Node using Mongoose? I need to update a user's email address, but first I have to ensure that the new email is not already associated with another user. This is what I want to achieve: /***************************** ...

Position a moveable item in the middle of two designated drop zones

I have been experimenting with creating a drag-and-drop feature that allows the draggable object to be placed between two droppable targets. The goal is for both droppable targets to receive and acknowledge the draggable object simultaneously, updating the ...

What is the best way to incorporate an image within a datatable?

How can I display an image in my datatable when the data is a json array of arrays? Data: [["1", "John","image1.jpg"], ["2", "Jim", "image2.jpg"]] I only have the name of the image in my database and I'm unsure how to show the actual image. ...

Adding list elements within a bootstrap `<li class="list-group-item"> using JavaScript is a simple process

Bootstrap is giving me trouble when I try to add a list. The list ends up outside of my Bootstrap code instead... Here is the image of the output I am seeing: https://i.sstatic.net/XhXAw.png My Code: var title = document.getElementById('title&ap ...

Disappearing Cloned Form Fields in jQuery

Hey there! I'm trying to duplicate a section of a form using the code below. But for some reason, the copied fields are only visible for a split-second before they disappear. Can anyone spot any errors that might be causing this strange behavior? jQu ...

Tips for bringing in and adding an excel spreadsheet to a kendo grid with the help of JQuery

I am facing a challenge with my kendo grid as I am trying to incorporate an excel file into it. Specifically, I would like to import and add an excel file to my kendo grid. If, for instance, my kendo grid initially has 3 rows, after importing an excel file ...

How can I pass a JSON object from CefSharp's ChromiumWebBrowser to JavaScript without converting it to a string?

browser.JavascriptObjectRepository.Register("BrowerFunc", new BrowerFunc(), isAsync: false, options: bo); public class BrowerFunc { public string readIniData(string Section, string iniFilePath) { string Conte ...