What is the process for comparing two objects in TypeScript?

There is a unique class named tax.

    export class tax {
        private _id: string;
        private _name: string;
        private _percentage: number;

        constructor(id: string = "", taxName: string = "", percentage: number = 0) {
            this._id = id;
            this._name = taxName;
            this._percentage = percentage;
        }

        public get id(): string {
            return this._id;
        }

        public set id(v: string) {
            this._id = v;
        }
        public get name(): string {
            return this._name;
        }

        public set name(v: string) {
            this._name = v;
        }
        public get percentage(): number {
            return this._percentage;
        }

        public set percentage(v: number) {
            this._percentage = v;
        }

        toString(){
            return this.id;
        }
    }

If two objects of this class are created:

    a1: tax = new tax("id","name",4);
    a2: tax = new tax("id","name",4); 

    console.log(a1 === a2); //false
    console.log(a1 == a2); //false

In order for `a1 === a2` to return true, what modifications should be made in the class? Which method needs to be overridden in the tax class?

Answer №1

When comparing instances of the same class, it's important to remember that they are unique entities even if their values may be the same.

For instance, consider a class called Animals with a property species. Even if there are two animals both classified as Lion, they are still distinct creatures.

Each instance comes with its own identity.

To determine if two objects share identical properties, you can compare them individually like so:

console.log(a1.getID() === a2.getID() && a1.getType() === a2.getType()) // true

For more insights on comparing objects in JavaScript, check out this resource.

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 entering text into a Code Mirror line using Selenium?

When I use IE to enter text into a CodeMirror-line text box, the text disappears when I try to save it. I have attempted using JavascriptExecutor to write to the CodeMirror, but it seems to only be for visual purposes. How can I input text into the code mi ...

Identifying the presence of a mouse inside an element using jQuery

I am working on a website that utilizes jQuery. The structure of my page is as follows: <div id="page"> <!-- Content goes here --> <div id="content"> <div class="row"> <div class="col"><!-- content goes here ...

Ways to ensure the synchronous execution of asynchronously invoked functions

I'm currently navigating the world of asynchronous code and trying to grasp its workings. As I construct a Node Express application that interfaces with a database, my aim is for it to interact with a Sqlite database in a development setting. (The pr ...

Prevent the ability to drag and drop within specific div elements

Having trouble disabling the sortable function when the ui ID is set to "comp". Can't figure out what's going wrong, hoping for some assistance here. $(".sort").sortable({ // start sortable connectWith: ".sort", receive: function ...

Learn how to automatically update data in Vue JS after making a 'POST,' 'DELETE,' or 'PUT' request in Vue JS 2

Whenever I send a 'POST' or 'DELETE' request, the data doesn't update automatically. I have to manually reload the page to see the updated information. Is there an easy way to refresh the data after making any 'POST' / &a ...

Understanding how flex-wrap property works in flexbox is essential for creating

Take a look at the code snippet below: .flex-container { padding: 20px; margin: 20px; list-style: none; border: 1px solid silver; -ms-box-orient: horizontal; display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -moz- ...

Downloading fonts from Google Fonts is always a struggle when using Next.js

After initializing a fresh Next.js project using create-next-app, I managed to successfully launch it with npm run dev. However, an issue arises every time Next.js boots up, displaying the following error: FetchError: request to https://fonts.gstatic.com/ ...

NodeJS unexpectedly exhibiting peculiar array functions

Within my NodeJS code, I have the following implementation: /* server.js */ 'use strict'; const http = require('http'), url = require('url'); METHODS = ['GET','POST','PUT','DELETE&a ...

Encountered an error with Winston and Elasticsearch integration: "TypeError: Elasticsearch is not a constructor

I recently implemented winston-elasticsearch on my express server by following the code provided in the documentation var winston = require('winston'); var Elasticsearch = require('winston-elasticsearch'); var esTransportOpts = { le ...

Efficiency boost: Implementing ajax to load content

Let's discuss the best methods for optimizing content loading with ajax. I will outline a few techniques and provide my insights on each one. Loading html directly - This method makes it easy to load content without much additional processing requir ...

ESLint error: EROFS read-only does not correspond to any directory

Can anyone help me with this issue? I am experiencing a problem when using Linux dual boot, but everything works fine when I use Windows. ERROR in [eslint] EROFS: read-only file system, open '/media/naufal/6878124278121004/Refactory/Skill-Test-Re ...

reveal concealed section and seamlessly glide to specified location inside the secret compartment

I have implemented a feature on my website where hidden divs are revealed one at a time, with the screen scrolling to display each specific div. While this code functions well, I am now looking to enhance it by opening the hidden div and smoothly scrolling ...

Unable to apply ready function in jquery .load

When the document is ready, the following code is executed: jQuery(document).ready(function(){ jQuery('#button').click(function() { jQuery('#contact_form').load("/Users/mge/Downloads/jquery-ajax-1/readme.txt"); ...

Adjust Navbar Header Color Based on Screen Size

I am completely new to front-end development. I am in the process of building my own responsive website using Bootstrap 3. One issue I am facing is that when I resize my browser window to simulate a phone screen, I want the navigation bar color to change ...

Utilizing Next.js and React to interact with Open AI through API requests

I'm currently experimenting with the OpenAI API to develop a chatbot using React, TypeScript, and Next.js. I am facing an issue where clicking the send button in the UI does not trigger any action. Even after adding console.log statements, nothing sho ...

I encountered difficulty in assigning a JSON response to a variable, both with and without using JSON.parse()

I'm in the process of creating a website that, among other things (and crucially for this particular issue), stores your current location data in a variable by fetching it from the ipinfo API (https://ipinfo.io/json) After encountering the problem of ...

- "Queries about Javascript answered with a drop-down twist

Having some trouble with setting up a straightforward FAQ dropdown feature. Could someone lend a hand and see what might be going wrong? Appreciate your help! CSS #faqs h3 { cursor:pointer; } #faqs h3.active { color:#d74646; } #faqs div { height:0; o ...

Clicking on the initial link will in turn prompt clicks on the subsequent links

Can you please provide instructions on how to correctly simulate a click on the remaining links if a click is made on the first link? jQuery('a.one_num').click(function() { jQuery('a.two_num').click(); jQuery('a.three_num&ap ...

Attempting to transmit JavaScript information to my NodeJS server

Having some trouble sending geolocation data to NodeJS through a POST request. When I check the console log in my NodeJS code, it's just showing an empty object. I've already tested it with postman and had no issues receiving the data. The probl ...

Managing the display of numerous ngFor components

If you're interested in learning more about the features I will include, here's a brief overview. I plan to have a project section with cards displayed for each project, all populated from a JSON file. When users click on a card on the website, a ...