How to compare various values from two different Objects and then store them in an array-type variable

Below are two sets of data for objects:

{
    "obj1": {
        "product": "Book",
        "category": "sci-fi",
        "title": "interstellar",
    },
    "obj2": {
        "product": "Book",
        "category": "horror",
        "title": "evil dead",                   
    },
   "differences": []
}

Using this data, I am looking to compare the values of obj1 and obj2 to identify keys that have differing values between the two objects and place them in the differences variable.

Expected Outcome:

{
    "obj1": {
        "product": "Book",
        "category": "sci-fi",
        "title": "interstellar",
    },
    "obj2": {
        "product": "Book",
        "category": "horror",
        "title": "evil dead",                   
    },
   "differences": [
        "category",
        "title"
   ]
}

Does anyone have any suggestions on how to solve this?

Answer №1

To compare two objects, create two loops - one for each object - and then compare their keys:

let data = {
  "obj1": {
    "product": "Book",
    "category": "sci-fi",
    "title": "interstellar",
  },
  "obj2": {
    "product": "Book",
    "category": "horror",
    "title": "evil dead",
  },
  "differences": []
};

for (let key1 in data.obj1) {
  for (let key2 in data.obj2) {
    if (key1 === key2 && data.obj1[key1] !== data.obj2[key2]) {
      data.differences.push(key1);
    }
  }
}
console.log(data);

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

I am attempting to create a skybox, yet it seems like I am overlooking a crucial element

Currently, I am attempting to create a skybox but have encountered difficulties with various tutorials. Initially, I tried to use an array approach to pass parameters for the material based on a previous example, but it seems that the method has been updat ...

Internet Explorer is throwing unexpected routing errors in Angular 2

I have a spring-boot/angular 2 application that is working perfectly fine on Chrome, Safari, Opera, and Edge. However, when accessed through Internet Explorer, the app directly routes to the PageNotFound component. I have tried adding shims for IE in the i ...

Modal failing to update with latest information

My webpage dynamically loads data from a database and presents it in divs, each with a "View" button that triggers the method onclick="getdetails(this)". This method successfully creates a modal with the corresponding data. function getdetails(par) { ...

Node.js is raising an error regarding strict mode, despite the fact that Babel 6 preset es2015 is being used, which

When working with node js, I encountered an error message stating uncaughtException: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode, despite using babel 6 es2015 preset which should include use strict. My pro ...

Clearing Time Field Input in Safari

Recently, I've been utilizing the following HTML input element: <input type="time"> While testing it in both Chrome and Safari, I noticed that the clear field (cross button) is absent when using Safari. How can I make the cross button appear i ...

Date Range Selection Widget malfunctioning when used within a popup modal

Having trouble with integrating the rsuite daterangepicker and antd's daterangepicker into a React Material UI Dialog/Modal. The date picker popup seems to either not show up or appear outside of the modal window. Take a look at the image below: Clic ...

Is it possible to access the passed arguments in the test description using jest-each?

Utilizing TypeScript and Jest, consider this sample test which can be found at https://jestjs.io/docs/api#testeachtablename-fn-timeout it.each([ { numbers: [1, 2, 3] }, { numbers: [4, 5, 6] } ])('Test case %#: Amount is $numbers.length =&g ...

Tips for integrating the legacy Twitter API method into an ASP.Net website

In the past, I utilized a method to display tweets from my Twitter account on a feed for my website customers: <ul id="twitter_update_list"><li>Twitter feed loading</li></ul> <script type="text/javascript" src="http://twitter.co ...

What is the process for exporting libraries in TypeScript?

Encountering an error when attempting to export socket.io using this method import socketIOClient from 'socket.io-client';. The error message is TS1192: Module '"***/node_modules/socket.io-client/build/index"' has no default e ...

Developing a pop-up feature that triggers upon clicking for a miniature rich text editing

Looking to integrate the Tiny rich text editor into my code. Check out the TextEditor.js component below: import React from 'react'; import { Editor } from '@tinymce/tinymce-react'; class App extends React.Component { handleEditorCha ...

Displaying a div upon hovering over another div is resulting in numerous server requests and a flickering effect

I am attempting to create a hover effect where one div floats next to another. The layout of the divs is like a grid, placed side by side. Check out my code on this fiddle. Using plain JavaScript, I want to display a second div (div2) floating next to div ...

Select elements using jQuery in events while excluding others

I need to prevent form submission when the user presses Enter, except for three specific inputs. To prevent form submission on Enter key press, I can use this code: $(document).keydown(function(event){ if(event.keyCode == 13) { event.preventDefault(); re ...

Sort users by their data attribute using jQuery

I need to sort users based on their data attribute. Within the main div called user-append, I have a variable number of users retrieved from an ajax get request. It could be 3 users or even up to 100, it's dynamic. Here is the structure with one user ...

Determining block time based on block number within Polygon Mumbai Testnet

Is there a dependable method to identify the production time of a specific block in Polygon Mumbai Testnet using only its block number? I am unable to utilize an Api for this purpose and am seeking a more user-friendly computational solution. Any suggest ...

Encountering the issue of "Unknown provider" while injecting Angular modules

After following a tutorial on organizing an Angular project, I came up with a structure where I have a ng directory containing all my controllers, services, and the routes.js file. These are then bundled together into an app.js through my configuration in ...

The foreach loop speeds through its iterations

Here is the loop that I am currently working on: client.users.forEach(user => { if (user.presence.status == "online") { fnHistory.userUpdate(user.id, status, false, message); } }); The function being called within this loop is as follo ...

What are some ways to create a ui-view that maintains its content without refreshing automatically?

My application utilizes 2 ui-views to display content - one for the friendlist and the other for a specific view: <div class="container-fluid h100"> <div ui-view class="h100"> </div> <div ui-view="connected"> </div> ...

Using data binding in VueJS to construct a dynamic URL

Exploring VueJS for the first time and it's been a great experience so far. However, I'm facing a couple of challenges with data binding. The requirement is for the customer to input an image URL, and no image should be displayed until a valid ...

JavaScript: Activate the element with the first class of its children

This code is a visual representation of what I'm trying to accomplish... <style> .red{background:red} .blue{background:blue} </style> <div id=test> <button>1</button> <button>2</button> </div> ...

Formulate an array by combining the values from two preexisting arrays

I am dealing with 2 arrays: Array ( [0] => 15 [1] => 15 [2] => 18 [3] => 18 [4] => 19 [5] => 21 [6] => 21 [7] => 21 ) Array ( [0] => 13 [1] => 14 ...