What is the best way to evaluate two objects with varying data types?

Is it possible to compare two objects with different data types?

var a = {
sort: 7,
start: "0"}

var b = {
sort: "7",
start: "0"}

I thought they should be equal, but when I try using

JSON.stringify(a) === JSON.stringify(b)
, it returns false.

Answer №1

One strategy to achieve this is by converting the objects into strings, then using a reviver function for parsing to convert the strings into numbers. After that, you can convert them back into strings and compare them:

var objA = {
  value: 7,
  start: "0",
  code: "a"
}

var objB = {
  value: "7",
  start: "0",
  code: "a"
}

const strA = JSON.stringify(objA);
const strB = JSON.stringify(objB);

const parsedA = JSON.parse(strA, (key, val) => {  
  return key && !isNaN(+val) ? +val : val;
})

const parsedB = JSON.parse(strB, (key, val) => {
  return key && !isNaN(+val) ? +val : val;
})

const areEqual = JSON.stringify(parsedA) === JSON.stringify(parsedB);

console.log(areEqual);

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

Trigger an Angular controller within Foundation's reveal modal

Trying to implement a form using foundation's reveal modal, I want to incorporate an angular controller within the form for ajax form submission instead of the default post/refresh behavior. This is my primary view: <html lang="es" ng-app="crm"&g ...

The Safari browser restricts interaction with password inputs but allows interaction with other types of input fields

My password input field is styled like this: <input class="genericButton" id="login-password" type="password" name ="password" placeholder="Password"> While everything functions correctly in Chrome, I encounter an issue with Safari. When I try to i ...

Enhance the v-autocomplete dropdown with a personalized touch by adding a custom

Currently utilizing the v-autocomplete component from Vuetify, and I am interested in incorporating a custom element into its dropdown menu. You can see the specific part I want to add highlighted with a red arrow in this screenshot: This is the current s ...

What is the most effective way to compare a nested array using the map or filter function in order to return only the first match

Here is a code snippet showcasing the data object containing information for the codeworks array with code and text values. There is a key array named code = ["ABC","MDH"] and the expected output is displayed in the following code snippets. const data = ...

Load information into a different entity

I need help with adding new values to an existing object. When I receive some form data from noteValue, I also have additional input data in my component under person that I would like to integrate into noteValue before saving it. let noteValue = form.va ...

Does JSX have an API that can handle self-closing tags, such as <br>, if they are not closed properly?

For my latest project, I've been working on a ReactJS component using JSX and it looks something like this: <script type="text/jsx"> var HelloWorld = React.createClass({ render: function() { return ( < ...

Which JavaScript framework tackles the challenges of managing asynchronous flow, callbacks, and closures?

I have a strong aversion to JavaScript. I find it to be quite messy and disorganized as a language. However, I recognize that my lack of proficiency in coding with it may contribute to this perception. These past few days have been incredibly frustrating ...

The issue lies with Express Mongoose failing to store the data

Encountering some issues when trying to save an object created in Express nodejs using mongoose. Despite receiving a confirmation that the object is saved, it cannot be located even after attempting to access it through the server. Express route for savi ...

What is the method for viewing the content within div tags on an apex page?

Locationbox is a system outside of Salesforce, similar to Google Maps. An example can be viewed here; I am aiming to integrate it into the Salesforce platform. The first script tag fetches JavaScript code from the Locationbox service. Once the startup() f ...

Accessing PHP output within Jquery

Even though I know PHP is a server-side script and JavaScript is client-side, I encountered an issue. I struggled to bypass browser security when making an AJAX request to another domain. Feeling lost, I decided to turn to PHP for help. The challenge I f ...

Utilizing JSON for sending model data to a controller in ASP.NET Core

I'm a beginner with ASP.NET Core and I'm attempting to send a view model to my controller. Data Model: public class ToolModel { public ToolModel() { } public string text { get; set; } public string type { get; set; } public stri ...

Leveraging the power of the three.js library on the client-side within a vue.js/n

I'm facing a challenge with incorporating the three.js library (installed via npm) to display 3D models on the client side within my nuxt.js application. Despite multiple attempts, I seem to be hitting a roadblock with the import not functioning prope ...

Switch out the HTML content within the JavaScript include

Here is the situation: <script type="text/javascript" src="http://xy.com/something.js"></script> This code snippet in my PHP/HTML file loads the entire something.js file. Inside that file, there are lines containing "document.write..." which ...

What is the best way to create a new row within a Bootstrap table?

Struggling to format an array inside a table with the `.join()` method. The goal is to have each car on a separate row. Attempts using `.join("\r\n")` and `.join("<br />")` have been unsuccessful. What am I overlooking? ...

Dynamically populate 7 select boxes with options using JQuery

I have a webpage that includes 14 different dropdown menus, one for each day of the week (Monday to Sunday). Each day has two dropdowns: one for opening time and one for closing time. I used jQuery to populate all 14 dropdowns with a pre-defined list of ho ...

The server mistakenly sent the resource as a Stylesheet even though it was interpreted differently

Dear Fellow Coders, Could anyone lend a hand? I encountered this issue on my website after uploading it to my FTP: "Resource interpreted as Stylesheet but transferred with MIME type text/plain" </head> <body> <div class= "navbar navbar ...

What is the proper way to invoke a function in the code-behind using JavaScript?

I need to invoke a function in the code behind from JavaScript Button : <button class = "btn btn-outline btn-danger dim" type = "button" onclick = "confirmDelete ()"> <i class = "fa fa-trash"> </i> ...

How to link a CSS file from a JavaScript file

I have a form for users with fields for first name, last name, password, and confirm password. I've implemented validation to check if the password and confirm password fields match using JavaScript: $(document).ready(function() { $("#addUser").cl ...

Ways to eliminate all attributes and their corresponding values within HTML tags

Hey there, I'm trying to strip away all the attribute values and styles from a tag in html Here's my Input: <div id="content"> <span id="span" data-span="a" aria-describedby="span">span</span> <p class="a b c" style=" ...

Tips for avoiding Netlify's error treatment of warnings due to process.env.CI being set to true

Recently, I encountered an issue with deploying new projects on Netlify. After reviewing the logs, I noticed a message that had never appeared during previous successful deployments: The build failed while treating warnings as errors due to process.env.CI ...