Determining Equality in JavaScript: Comparing 2 Objects

I'm currently working with 2 objects that will always have the same amount of properties, but their values may vary.

In my attempt to check if the two objects hold the same values, I decided to use the .every method. However, all results are returning false, even though I am expecting them to be true.

How can I compare these 2 objects to determine if they are equal?

Below is a snippet of the code:

const priceOne = {
"price": 14.31,
"taxes": 2.00,
"total": 16.31
}

const priceTwo = {
"price": 14.31,
"taxes": 2.00,
"total": 16.31
}

const comparePrice = Object.keys(priceOne).every((item, index) => {
      item === Object.keys(priceTwo)[index] ?  true :  false
    })
    
console.log(comparePrice)

Answer №1

When comparing different objects:

     const priceOne = {
            "price": 14.31,
            "taxes": 2.00,
            "total": 16.31
      }

      const priceTwo = {
            "price": 12.31,
            "taxes": 2.00,
            "total": 16.31
        }

let comparePrice = true

 for (let key in priceOne){
    if(priceOne[key] != priceTwo[key]){
       comparePrice = false
     }
 

The variable will be false when the objects are identical:

const priceOne = {
       "price": 14.31,
       "taxes": 2.00,
       "total": 16.31
 }

const priceTwo = {
      "price": 14.31,
      "taxes": 2.00,
      "total": 16.31
}

In this case, the result will be true.

I hope this explanation is helpful

If we encounter an array instead of a string or number, we can easily add additional validation using this approach:

 const priceOne = { a: '0' };

 const priceTwo = { a: [0] };

 let comparePrice = true

for (let key in priceOne) {

if(Array.isArray(priceTwo[key] )){
    if (priceOne[key] != priceTwo[key].toString()) {
    comparePrice = false
  }
}else if(Array.isArray(priceOne[key] )) {
    if (priceOne[key].toString() != priceTwo[key]) {
    comparePrice = false
  }
}
if (priceOne[key] != priceTwo[key]) {
    comparePrice = false
   }
}

console.log(comparePrice);

Answer №2

To compare prices, I recommend using JSON.stringify(). For example:

if ( JSON.stringify(itemPrice) === JSON.stringify(productPrice) ){ 

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

"Encountered a 400 Error while trying to access the OpenAI

var openairequest = new XMLHttpRequest(); const payload = ({ "model": "text-davinci-003", "prompt": "say this is a test" }); console.log(payload) openairequest.open("POST",`https://api.openai.com/v ...

Retrieve the past week's data based on names using JavaScript

Is there a way to dynamically fetch the past seven day names, starting from today, in JavaScript? I am looking to format the result as follows: (Wednesday, Tuesday, Monday, Sunday, Saturday, Friday, Thursday, Wednesday). ...

Tips for adjusting font size automatically to fit within its parent container every time

On my blog, the post titles are displayed in a div with a video playing in the background. The length of the title varies, ranging from 2 words to over 20 words. When the title is too long, it may overflow from its parent container where the video is playi ...

What could be causing my Angular JS application to malfunction?

Presenting myFirstAngularApp.html <html ng-app="store"><!-- The "ng-app" attribute initializes an Angular app. Everything inside this tag is considered part of the Angular app due to ng-app --> <head> <link rel="stylesheet" type= ...

What could be causing the "ERROR TypeError: Cannot read property 'length' of undefined" message to occur with a defined array in my code?

Even though I defined and initialized my array twice, I am encountering a runtime error: "ERROR TypeError: Cannot read property 'length' of undefined." I have double-checked the definition of the array in my code, but Angular seems to be playing ...

Challenge with delayed function execution in AngularJS

In my Angular application, I am encountering a problem in the following scenario. There are three crucial files: MainCtrl.js Upon loading the application, the init() function in MainCtrl.js is triggered, which then calls the flowService as shown below: ...

The readStream in Node.JS unexpectedly terminates before the writeStream

I'm currently working on a project that involves fetching PDF files from remote servers and immediately sending them back to the clients who made the request. Here is the code snippet I am using: var writeStream = fs.createWriteStream(filename); writ ...

Retrieve the element that triggered the event listener within Nuxt

I am currently developing a Nuxt project where I have set up my component using the code below. The select-parent-container has a click event attached to it. Whenever this event is triggered, I need to identify and return the specific parent container that ...

Find the identifier that does not currently exist in the collection of objects

There is a situation where I have an array and an object that consists of arrays of ids, which are essentially permission objects. My goal now is to extract the ids that do not exist in the given object. Can someone assist me with devising the necessary l ...

Load and execute a dynamically created script in JavaScript at the same time

I am exploring the option to load and evaluate a script from a third-party synchronously. Here is an example that currently works well: <head> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

The useMutation function trapped in an endless loop

I've been encountering an issue while running a query to save an entity in the database using usemutation. The saveVisa() mutation seems to be stuck in an infinite loop, creating the same element multiple times without any clear reason. import {React, ...

Reset dropdown selection when a search query is made

Currently experimenting with Angular to develop a proof of concept. Utilizing a functional plunker where selecting an option from a dropdown populates a list of items from an $http.get( ). Additionally, there is a search input that should trigger its own $ ...

Raycasting intersection with a line on BufferGeometry in Three.js

After successfully implementing raycasting on lines with R59 and displaying tooltips on mouseover, I encountered performance issues due to increasing data. This led me to switch from using THREE.Geometry to THREE.BufferGeometry. While everything else seems ...

Using AngularJS to filter an array using the $filter function

Looking for a more elegant way to achieve the following task: myList.forEach(function(element){ if (!['state1', 'state2'].contains(element.state)){ myFilteredList.push(element) } }) I was thinking of using $filter('fi ...

Using jQuery to manipulate the image within a specific div element

I'm facing an issue with locating the img src within a div. I've written a function to find all the divs with specific ids: function identifyDiv(){ divArray = $("div[id^='your']"); divArray = _.shuffle(divArray); } This is the ...

I require a way to decelerate the speed of the roulette wheel's rotation

For my assignment, I'm tasked with creating a roulette spin wheel code in JavaScript without using any plugins. I need to incorporate some conditions before executing the code, particularly for slowing down the speed of the roulette spin. Additionally ...

Successful execution occurring prior to beforeSend in a Cordova iOS application utilizing jQuery Ajax

After making some changes to the HTML of the login button, I encountered an issue where the alert was being triggered before the button's HTML had updated when testing on my iPhone using a Cordova-built app. Strangely, this problem did not occur when ...

Trigger a notification based on the selected choice

Here is some sample HTML code: <div id="hiddenDiv" style="display: none;"> <h1 id="welcomehowareyou">How are you feeling today?</h1> <select name="mood" id="mood"> <option value="" disabled selected>How are you feeling?</o ...

Adding an onClick event to a React MUI Fab: A Step-by-Step Guide

I'm attempting to incorporate the Floating Action Button from MUI5. Visit: https://mui.com/material-ui/react-floating-action-button/ for more details. Upon adding an onClick event to the button, no action is triggered. Below is my code snippet: <G ...

Customizing event colors in Full Calendar

My interactive calendar is created using : $('#calendar').fullCalendar({ height: 300, //............. events: jsonData, month: firstMonth }) I am looking to dynamically change the color of an event based on certain conditions ...