Is there a way to confirm if two JavaScript Objects share identical keys?

My task involves comparing two large JavaScript Objects, each containing approximately 200 keys. The keys in the objects are unordered and have different values, but I am only interested in whether they share the same set of keys. If both objects have the same keys, the function should return true regardless of their order.

I attempted to use the following code, but it did not work as expected:

var compareObjects = function (object1, object2) {
    let keysObj1 = Object.keys(object1);
    let keysObj2 = Object.keys(object2);
    
    for (key in keysObj1){
        if (!keysObj2.includes(key)){
            console.log("Missing key in object2: ", key);
        }
    }
}

Example:

{"key1": "val", "key2": "sdsfaf"}
{"Key2": "val", "key1": "vsdsdsd"}
This should return true
{"key1": "val", "key2": "sdsfaf"}
{"Key2": "val"}
This shouldn't

Answer №1

Retrieve the unique keys of the objects using new Set(Object.keys(a)) and new Set(Object.keys(b)).

You can then compare these sets by following this method: comparing ECMA6 sets for equality

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 method for ensuring that a GreaseMonkey script impacts elements on a page prior to their appearance?

I'm currently working on a project that requires hiding images on a specific website while still displaying the alt text. Initially, I tried to achieve this using Stylish on Firefox and posted the following question: How to force an image's alt ...

Arrange moving shapes in the same spot

Every time I press the button, a unique shape is generated. These shapes are dynamic and can range from polygons to circles (there are hundreds of shapes). Each shape is composed of a series of lines. The problem arises when each shape is positioned diff ...

"Can we apply a filter to the JSON file when it is

I encountered an issue while trying to filter json data based on user selection. The debugger console displayed the error message: TypeError: obj.contacts.filter is not a function. I have included a snippet of my code below: var contactStorage = {}; $(" ...

Using the next/dynamic library to import components in Next.js can be complex and confusing at first

Embarking on my first foray into building a NextJs app for production, I find myself in uncharted territory as a newcomer. My current project involves incorporating PeerJs for real-time communication, yet encountering an issue when attempting to import it ...

Ways to transform a PHP function into one that can be invoked using Ajax

In my current project, I’m facing an issue where I need to call multiple PHP functions that output HTML using Ajax. Instead of directly trying to call a PHP function with Javascript, I believe application routing can help the frontend hit the correct fun ...

A technique for combining the elements of one array in a loop and then transferring them to another array before adding them to an object

In order to streamline the process of calculating tip percentages based on bill amounts, I have developed a method within the object itself. However, to prevent redundancy, I have also created a separate function called calculateTip and a dedicated for loo ...

Retrieve a file from a server using Angular's $http.get method

My goal is to initiate a file download when a user clicks on a "Download PDF" button. The API is called, performs some validations, and then returns the file. I want to ensure that the file does not open in the browser and instead prompts the user to save ...

Using the integrated pipeline mode in IIS is necessary for this operation to be

My aspx page has an ajax call which looks like this: $.ajax({ url: "/SiteAdmin3/UpsIntegration.aspx/addUpdatePackageData", data: JSON.stringify({ '_OrderNumber': $("#txtOrderNumber ...

The CSS file is failing to recognize the changes made to the data-theme attribute in the HTML

Currently implementing a dark theme on my website involves adding a toggle switch to the footer.html page, which adds a variable named data-theme = 'dark' to the html. The scss files of the footer and core are adjusting accordingly based on the c ...

"Exploring the process of unsubscribing or disposing of an interval observable based on a certain condition in Angular2 or

I am embarking on the journey into Rx and reactive programming, facing a situation that requires me to continuously monitor a hardware's status by sending a POST request to its REST API every 500ms. The goal is to stop the interval observable once the ...

the click event fails to trigger when the id or class is modified

Hey there, I'm new to working with jquery and I've encountered a problem. Here's the code snippet: http://jsfiddle.net/8guzD/ $('#test.off').click(function(){ $(this).removeClass('off').addClass('on'); }) ...

The createElement function in Vue.js does not always return a fully formed component

There is a scenario where I need to create a functional component for a specific purpose. The task at hand involves taking all the children elements and adding some additional props to them, but only to those that are custom components of type ChildCompone ...

Setting focus on the require attribute for the <input> tag in a React application

I have a login/register form with multiple input tags. My goal is to automatically set focus and require attribute on the first input tag when the form is opened. I have tried using jQuery and JavaScript to add the required attribute, which works fine. H ...

Toggle a Vue.js method to display responses for a particular question

Currently, I am in the process of developing a simple toggle feature for a FAQ section. The idea is that when a user clicks on an icon associated with a specific question, only that question's answer should be displayed. Although the function is oper ...

Do not include the loading of <embed> items while the page is loading

I am currently working on a website project for a friend that involves incorporating a lot of large images. To ensure a smooth loading process, I have implemented a loading overlay while the background content loads. However, I have also added background m ...

The ng-include directive is having trouble finding the partial HTML files

I've been working on setting up a basic tabset with each tab pulling content from a separate partial view with its own controller. To test everything out, I created three dummy HTML files with simple text only. However, I'm having trouble getting ...

Unfinished silhouette using THREE.js

I am new to JavaScript and THREE.js and seeking guidance. Below is the visual output I managed to create: https://i.sstatic.net/P1hWA.png Here's the code snippet: // Initializing the renderer renderer = new THREE.WebGLRenderer(); renderer.setSize ...

Matching patterns with regular expressions in Javascript

There's a string that goes like this: |Africa||Africans||African Society||Go Africa Go||Mafricano||Go Mafricano Go||West Africa|. I'm attempting to craft a regular expression that will only match terms containing the word Africa or any variation ...

Building a reusable Button component in React using TypeScript that handles not assignable type errors

Attempting to create a reusable component in reactjs using typescript is currently resulting in the following error: Type '{ children: string; type: string; }' is not assignable to type 'DetailedHTMLProps<ButtonHTMLAttributes<HTMLButt ...

Efficient ways to retrieve row values and remove data using DataTables

I am facing an issue with my DataTable setup. I have a column dedicated to details with a delete button within an href tag. However, when I try to add a class name or id to it, I encounter an error. You can view the example here. My goal is to be able to ...