Intensive analysis of objects comparing their characteristics

Currently delving into the world of Javascript, I encountered a coding exercise involving a "deepEqual" function that I attempted to write but ultimately struggled with. Even after reviewing the solution, one particular part perplexed me - the for loop, especially the !deepEqual(a[key], b[key])) segment. My confusion lies in why I cannot simply use (keysA[key] !== keysB[key]) or (a[key] !== b[key]). To me, it seems like the code is saying "if the values of the keys in objects a and b are not found in deepEqual, then return false," despite knowing that the values do exist. I fail to see where the actual comparison between these values takes place. Undoubtedly, my interpretation is flawed, so I am seeking clarification.

function deepEqual(a, b) {
  if (a === b) return true;

  if (a == null || typeof a != "object" ||
      b == null || typeof b != "object") return false;

  let keysA = Object.keys(a), keysB = Object.keys(b);

  if (keysA.length != keysB.length) return false;

  for (let key of keysA) {
    if (!keysB.includes(key) || !deepEqual(a[key], b[key])) return false;
  }
  return true;
}

let obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true

Answer №1

It's not as simple as checking a[key] != b[key] because these values could be objects. Comparing objects requires a recursive comparison of their contents, which is why the deepEqual() function was created in the first place.

This part of the code:

if (!keysB.includes(key) || !deepEqual(a[key], b[key])) return false;

essentially means that we will return false if b does not contain key as a property, or if the comparison of the nested key properties of both objects is not equal.

If the key exists and the nested objects are indeed equal, the loop continues with the next key.

The primary comparison at the beginning of the recursion occurs here:

if (a === b) return true;

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

Having trouble locating the web element within a div popup while utilizing Node.js and WebdriverIO

I need assistance with a seemingly simple task. I am currently learning webdriverjs and attempted to write a short code to register for an account on the FitBit website at URL: www.fitbit.com/signup. After entering my email and password, a popup appears as ...

Creating an Angular JS controller that utilizes a filter for a JSON array of objects

I have the following JSON data and I'm trying to determine the number of objects with Status: 1 in the JSON. The approach I've taken so far is not working. I understand that ng-filter should only be applied to Arrays, but I'm struggling to ...

When using v-for to render components and <selection>, is there a way to customize it for just one specific instance of the component?

How can I modify the selection in each instance separately when rendering elements of an array obtained from the backend using v-for? Currently, changing one selection affects all instances due to the v-model. Is there a way to target only one selection ...

What is the process for obtaining the hash of every hyperlink?

I'm currently working on implementing an active link state based on scroll position for each section. My goal is to extract the hash value from the link. The issue I'm facing is that when I run the line 'console.log($(this).eq(i).hash);&ap ...

Getting the location of a mouse click and adding tags (marks) on an image: a simple guide

Is there a way to incorporate images with tagged marks similar to Facebook's image tagging feature? How can I retrieve the X and Y coordinates of tags on the image itself (not the screen) and display them in a responsive manner? ...

Tips on integrating the createjs library into a ReactJS project

Hey there! I'm currently working on developing a canvas-based app using ReactJS, and I need to integrate the CreateJS library. As a newcomer to ReactJS, I've been struggling to figure out the best approach. I've tried two different methods - ...

What is the best way to connect to my shop through RTK-Query API?

Is there a way to access my redux-toolkit store data from within the rtk-query endpoints? How can I retrieve information from my store in the query or transformResponse methods? import { createApi } from '@reduxjs/toolkit/query/react' import cus ...

How to properly format an HTML input box for numeric entry and ensure correct formatting of the minus sign

I need assistance with formatting an HTML text input box to only accept numeric values using JavaScript. Specifically, the input should allow digits, a minus sign, or a dot/comma (which will be converted to a dot). However, I want to prevent multiple conse ...

How can you update an image's source when hovering over it?

My goal is to switch the image source upon mouseover using a combination of asp.net and javascript. Here is the code I am currently using: <asp:ImageButton id="button" runat="server" Height="65px" ImageUrl="~/images/logo.png" OnMouseOver="src='~ ...

Experiencing difficulties with JWT implementation and seeking to transmit the JWT token to additional APIs

I am currently working on implementing JWT authentication in node js/express js: Below is the sample code I have written for this purpose: const jwt = require('jsonwebtoken'); const secretKey = crypto.randomBytes(64).toString('hex'); c ...

Ways to adjust a specific div within an ng repeat using the value from JSON in AngularJS

When I select a different option from the dropdown menu, such as cities or states, the values are populated from a JSON file. My specific requirement is to hide a button only when the value 'No data' is populated upon changing the dropdown select ...

Collaborating on user authorization within a MEAN.JS framework

Recently, I decided to dive into the world of web application development by using MEAN.js full stack solution. Using the generators within MEAN.js, I was able to effortlessly create multiple CRUD models along with all the necessary express routes. In ad ...

Where should the logic for the Redux app be implemented for optimal performance?

My react-redux app features an action-creator that filters a list of objects based on a specified title: export const filterItems = (title) => dispatch => { axios.get(`/api/items/?title=${title}`) .then(res => { dispatch({ ...

Use PipeTransform to apply multiple filters simultaneously

Is it possible to apply multiple filters with PipeTransform? I attempted the following: posts; postss; transform(items: any[]): any[] { if (items && items.length) this.posts = items.filter(it => it.library = it.library ...

Is there a way to activate a Superfish jQuery Menu with a click instead of a hover?

After doing some research on the internet, I came across an implementation of Superfish menu by Joel Birch that functions based on onclick instead of hover. I found a link on Github by Karl Swedberg which seems to be what I need. https://gist.github.com/ ...

Issues with zoom functionality not functioning properly within IE11

I am currently developing an application with Angular that is designed to be compatible with tablets and touch-enabled devices. One of the key features I want to implement is the ability for users to zoom/scale up the app, especially for those with visual ...

React - How to Close Material-UI Drawer from a Nested Menu

Currently, I am utilizing a fantastic example (here) to create a dynamic nested menu for my application. Taking it a step further, I am trying to integrate it into a Material UI appbar/temporary drawer. My goal is to close the drawer when the user clicks o ...

Accessing HP ALM with REST and JavaScript on a local server: A step-by-step guide

I am trying to access ALM using locally written JavaScript in the browser (IE11, Firefox) through the REST API, but I am unable to login. Below is the code snippet where I am attempting to request the LWSSO cookie with jQuery: var auth = btoa(USER+":"+PAS ...

Tips on retrieving and showcasing information from various endpoints in React?

I am working with two different endpoints and I need to fetch data from both simultaneously in order to display it in one single element. For example, I want to show data from one table along with the corresponding name from another table if the product id ...

The act of employing `Function.prototype.run` within an Angular TypeScript class is deemed as illegitimate

Is there a way to globally define a new function called run within my Angular component as shown below? Function.prototype.run = function (delay: number) { // some content; }; However, the compiler shows an error that the Property 'run' does n ...