The issue with Lodash isEqual arises from the constructor specified by Angular

Currently, I am utilizing Lodash _.isEqual for performing a deep comparison between a local JavaScript object and another JavaScript object fetched through angular $get.

The initial code indicates that the objects are not the same:

$get({...}, function (data) {

  cleanupAngularProps(data);

  if (_.isEqual(data, {name: 'Someone'}) {
    ...
  }
});

However, after making a slight adjustment, the code now recognizes them as equal (as expected):

$get({...}, function (data) {

  cleanupAngularProps(data);

  if (_.isEqual(JSON.parse(JSON.stringify(data)), {name: 'Someone'}) {
    ...
  }
});

Upon debugging into the Lodash code, it appears to be failing due to the different constructors in both objects.

Is there a way to resolve this issue without having to clone the data?

Answer №1

Although this question is a few years old now, I wanted to share an alternative answer that I believe is more suitable. Instead of comparing the prototypes of the two objects:

var result = _.isEqual(
  _.omit(data, ['__proto__']),
  _.omit({name: 'John'}, ['__proto__'])
);

Answer №2

It may not be conventional, but I managed to fix the issue by resetting the prototype and constructor as shown below.

$fetch({...}, function (result) {

  clearProperties(result);

  result.__proto__ = Object.prototype;

  if (_.isEqual(result, {title: 'Company'}) {
    // Perform necessary actions
  }
});

Answer №3

In order to achieve a thorough comparison while disregarding constructors, the following code can be utilized:

const comparator = (x: any, y: any, identifier: any) => {
            if (_.isObject(x) && _.isObject(y)) {
                // @ts-ignore
                const xPrototype = x.__proto__.constructor.name
                // @ts-ignore
                const yPrototype = y.__proto__.constructor.name
                if (xPrototype != yPrototype) {
                    return _.isEqualWith(_.omit(x, ['__proto__']), _.omit(y, ['__proto__']), comparator)
                }
            }
            return undefined
        }
_.isEqualWith({bar:2}, {bar:2}, comparator)

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

Unable to modify document value in MongoDB using Node.js

Currently, I am attempting to fetch the value of a field form that is being sent to a subroute and utilize it to update a database collection. My ability to retrieve the form value and manipulate it is working fine; however, I encounter an issue when I sol ...

Issue with React-Native Picker - managing item selection

Encountering an issue with the Picker picker component. There is an array of currencies as strings. Using the Picker to select items from this array, and have a function included in the onValueChange prop in Picker. The problem arises when trying to select ...

Guide to adjusting the color of Fluent UI icon when hovering with mouse?

I've been implementing Fluent UI in my current project. When initializing my button, I use this straightforward JavaScript code: iconProps: { iconName: 'NewFolder', styles: { root: { color: 'orang ...

Modify the innerHTML to adjust font size when a button is clicked in Ionic 5, or eliminate any unnecessary spaces

I have been experimenting with changing the font size of a variable in .html when the variable contains whitespace. In my .ts page, I use the following code to remove the whitespace: this.contents = this.sanitizer.bypassSecurityTrustHtml(this.product[&apos ...

Can you explain the concept of transformRequest in AngularJS?

I'm dealing with a specific code snippet transformRequest: function(obj) { var str = []; for(var p in obj) str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); return str.join("&"); } This code ...

Using the <noscript> tag for an individual element or a comparable alternative

So, I have a link labeled "Impressum" that when clicked, opens up the Impressum section. <a data-open="something">Impressum</a> <div class="reveal" id="something" data-reveal> <img src="images/reverseLogo.png"> <h1>Imp ...

Getting the ID of a select input option in Vue.js using FormulateInput

Recently, I've been working with a FormulateInput select component that looks like this: <FormulateInput name="broj_zns-a" @change="setZns" :value="brojZnsa" type="select" label="Broj ZNS- ...

Show the date and time in a visually appealing way by using HTML and JavaScript in an HTA application with scrolling effects

I have the following JavaScript code to show the current date in the format Mon Jun 2 17:54:28 UTC+0530 2014 within an HTA (HTML application). Now, I would like to display it as a welcoming message along with the current system date and time: Mon Jun 2 17: ...

Inserting a Specific Iframe into a Designated Location in HTML with the Help of Jquery

Currently, I am encountering an issue with placing a dynamically created iframe inside a specific section of my webpage. The iframe is supposed to be contained within a div element named "maps", but instead it is appearing at the bottom of the page.This ma ...

Creating a tree structure from an array in JavaScript, including the parent id enclosed in brackets

Before dismissing this question as a duplicate, please listen to me. I am working with a json response in reactjs that looks like the following organisationUnits: [ { name: "0.Mzondo", id: "nW4j6JDVFGn", parent: { ...

reconfigure keyboard shortcuts in web browser

In the popular web browser Google Chrome, users can quickly jump to the next tab by pressing CTRL + TAB. Is there a way to change or disable this shortcut? The provided code snippet does not seem to work as intended. $(document).keydown(function(e){ ...

Error message in Angular when promises are not defined

Recently, I started working with promises for the first time. I have a function that returns a promise: public DatesGenerator(futercampaign: ICampaign, searchparam: any, i: number): ng.IPromise<any> { return this.$q((resolve, reject) => { ...

"Use jquerytools to create a dynamic play/pause button functionality for scrollable content

Greetings! I am currently working on creating a slide using Jquerytools. Here are some helpful links for reference: To view the gallery demonstration, please visit: For information on autoscroll functionality, check out: If you'd like to see my cod ...

Postponed in JQUERY | AJAX

My requirement is to retrieve data using the "SetUnit()" function, which includes asynchronous AJAX services. I attempted to use Deferred as suggested in this link, but it did not work for my needs. Code...... Function function SetUnit(query) { var ...

What is the method for retrieving values from an object using keys that are subject to change?

Here is the code snippet I am working with: bodyLength.forEach((el, i) => { console.log(`${values.bodyTitleEn2 + i.toString()}`); body.push({ title: [ { key: 'en', value: values.bodyTi ...

Modifying the default value setting in MUI Datepicker

Currently, I am utilizing version @mui/x-date-pickers ^6.17.0. Here is the custom date picker I am using: https://i.stack.imgur.com/k8nF1.png Upon clicking the input field, the placeholder switches and a value gets appended. However, modifying the input ...

Sending C# Model from View to Javascript

I have set up my ViewModel for the View: public class DashboardViewModel { public List<UserTask> UserTasks {get; set;} public List<WorkItem> WorkItems {get; set;} } In the View, I am looping through the WorkItems as follows: ...

What is the optimal arrangement for constructors or classes in JavaScript code?

Constructors, being objects that are stored as copies, appear to behave similarly to variables in terms of their placement within the code. Unlike functions, constructors cannot be placed "anywhere" and must instead be positioned above the area where they ...

Vue 3 Option api: Issue with v-model input not propagating from child component to parent element

I am currently working on a new project using Nuxt 3, and I have encountered an issue with a contact form where the input values from a child component are not being received by the parent element. Let's dive into the code breakdown: Parent Component ...

An issue arises when data from the parent ajax call is being referenced

I am encountering a situation where I have nested ajax functions within each other. $.ajax({ url: '../...', type: 'POST', dataType: 'JSON', ...