Can you suggest a way to revise this in order to include the type of property (string)?

Here is a snippet of working code that raises a question about refactoring to improve the readability and functionality. Consider renaming the method to isPropValueSame.

import * as _ from 'lodash';

const diff = _.differenceWith(sourceList, comparatorList, this.isSame);

isSame = (objA: any, objB: any) => (_.has(objA, 'id') && _.has(objB, 'id') ? objA['id'] === objB['id'] : false);

The goal is to pass a property name string like this.isSame('id'));

objA and objB represent items from lists: sourceList and comparatorList, which could look something like:

const sourceList = [
    { id: 1, prop2: { prop21: someValue }, prop3: prop3Value },
    { id: 2, prop2: { prop21: someValue }, prop3: prop3Value },
    { id: 3, prop2: { prop21: someValue }, prop3: prop3Value },
];
const comparatorList = [
    { id: 1, prop2: { prop21: someValue }, prop3: prop3Value },
    //{ id: 2, prop2: { prop21: someValue }, prop3: prop3Value },
    { id: 3, prop2: { prop21: someValue }, prop3: prop3Value },
];

In the given test case data (where the second item in comparatorList is commented out), the output of the comparator function would be the item with an id equal to 2 because it's not found during comparison by the isSame delegate function.

Answer №1

Maybe you're not interested in anything beyond wrapping the key - it appears that ensuring type safety isn't a priority, so here's a simple solution:

const isMatching = (key: string) => (objectA: unknown, objectB: unknown) =>
  _.has(objectA, key) && _.has(objectB, key) && _.get(objectA, key) === _.get(objectB, key);

Code Sandbox Demo

If you can do without type validation for the key, this should work fine. But if it's needed, check out this related answer on accessing paths recursively..

Answer №2

To efficiently compare objects based on a specific property, you can utilize a closure that takes the desired property as an argument:

const isEqual = (property) => {
  const equal = (a, b) => (_.has(a, property) && _.has(b, property) ? a[property] === b[property] : false);
  return equal;
};

const someKey = 42;
const propValue = 3;

const dataToCompare = [
  { id: 1, key2: { subkey: someKey }, prop3: propValue },
  { id: 2, key2: { subkey: someKey }, prop3: propValue },
  { id: 3, key2: { subkey: someKey }, prop3: propValue },
];
const referenceData = [
  { id: 1, key2: { subkey: someKey }, prop3: propValue },
  // { id: 2, key2: { subkey: someKey }, prop3: propValue },
  { id: 3, key2: { subkey: someKey }, prop3: propValue },
];

console.log(_.differenceWith(dataToCompare, referenceData, isEqual("id")));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

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 best way to ensure the height and width of a Next.js image matches the dimensions of the original image?

Currently, I am working on setting up an image gallery with a layout similar to Masonry. This layout involves multiple columns, all with the same width, adjusting based on the viewport width. The height of each item in the gallery is flexible, depending on ...

In a scenario where multiple fields need to be incremented, one can accomplish this by incrementing one field every time while also increasing the other field only if it exceeds a

When trying to decrement class_number, everything works fine. However, the issue lies with number_of_classes not being decremented due to the usage of the $gt operator. posts.update({ 'title':doc.title, 'author':doc.author, 'class ...

The parameter type 'string | VNode' does not align with the expected type 'VNode & string' for this argument

Hi there, I might be mistaken but I could really use some help with this issue I'm facing: Argument of type 'string | VNode' is not assignable to parameter of type 'VNode & string'. Type 'string' is not assign ...

Ways to Adjust the Earth's Position in WebGL Earth

I have been working with this WebGL Earth component for my project, but I am facing difficulty in adjusting the position of the planet on the canvas. My intention was to place the planet at the bottom of the page, but I haven't been able to achieve th ...

What is the process for adjusting the width of an element using JavaScript?

I have a unique bar with one half red and the other green. I am trying to subtract 1vw from the width of the red section. Unfortunately, using style.width is not yielding the desired result. See below for the code snippet I am currently using: //FIGHT do ...

Vee-Validate: Are flags on the field value yielding undefined results? Explained with TypeScript

The documentation states that by using a flag on the value of a field, I should be able to obtain a boolean. For example: computed: { isFormDirty() { return Object.keys(this.fields).some(key => this.fields[key].dirty); } }, I am working ...

What is the best method to retrieve the title from an array using javascript?

I am working with a JSON object containing information on thousands of students. I have converted this JSON object into an array, and below is an example of how one array looks: [ 'Alex', { id: '0.0010733333111112', grade: &apos ...

When utilizing the Page Object Model in Playwright with TypeScript, a Linting Error may occur, specifically a Parsing error related

Recently, I started using playwright and decided to implement the page object model using typescript. Everything was going smoothly until I ran a lint check. Unfortunately, the linting check failed in the Pull Request Check on GitHub. The error is occurri ...

Having trouble choosing options within Material UI's Autocomplete Component?

I'm having trouble selecting the options displayed in MUI's autocomplete component. It seems that using renderOption is causing this issue. I want to show an image along with the title in the component options, but without using renderOption, I h ...

The beforeunload event only triggers when the page is refreshed, not when the page is exited

I am currently utilizing the react-admin framework (version 3.2) and I am attempting to trigger the beforeunload event when a user is moving away from the Edit form view. For instance, if my pathname is "feed/123", I want the beforeunload event t ...

What is the process for implementing THREE.EdgesGeometry on a model imported using THREE.OBJLoader?

I have been attempting multiple times to add edges in a model loader using the OBJLoader, but I am unable to achieve it. Mloader = new THREE.MTLLoader(); Mloader.setPath( dir ); Mloader.load( mtl_dir, function ( materials ) { ...

Oops! It looks like there was an error. Remember that AJAX events should be connected to the

I am completely new to the world of Ajax and unfortunately, I encountered an error message in my browser: "JQMIGRATE: AJAX events should be attached to document: ajaxComplete" After some research, it seems like I need to incorporate certain Ajax functi ...

The function navigator.canShare() encountered a permissions denial while running in Typescript

Currently, I am in the process of developing an Angular8 PWA and have successfully implemented webshare to share text content. To my excitement, Chrome has now extended its support for file sharing starting from May 2019. However, while attempting to int ...

Creating a JSON schema for MongoDB using a TypeScript interface: a step-by-step guide

In order to enhance the quality of our data stored in MongoDB database, we have decided to implement JSON Schema validation. Since we are using typescript in our project and have interfaces for all our collections, I am seeking an efficient method to achie ...

Troubleshooting Paths with Angular's NgFor Directive

Within my Angular project, I have implemented a basic ngFor loop to display logo images. Here is a snippet of the code: <div *ngFor="let item of list" class="logo-wrapper"> <div class="customer-logo"> & ...

How to dynamically retrieve values from a const object literal using TypeScript

Currently, I am utilizing a TypeScript library known as ts-proto, which is responsible for generating TypeScript code. The resulting generated code resembles the following: //BasicMessage.ts export interface BasicMessage { id: Long; name: string; } ...

Having trouble with the JSON response while implementing AngularJS

Recently, I've started working with angularjs and ran into an issue where the data is not loading on the page when pulling JSON from a Joomla component. Strangely enough, everything works perfectly fine when I retrieve the data from a getcustomers.ph ...

Reorder elements using CSS when they do not share the same immediate parent container

I am looking to rearrange the order of some items on my page using JS or CSS. The project I am working on is written with ReactJS. Here is the basic structure: <div class="parent"> <form> <div class="header"></di ...

AppleScript: Check if the value of document.getElementById is empty, then fill in the value

Hello everyone, it's my first time asking a question here. I have an AppleScript that takes values from a Numbers document and fills them into different fields of a webform using document.getElementById. Everything is working perfectly so far, but now ...

Help! I keep getting the NullInjectorError in the console saying there is no provider for Subscription. Why is this happening?

Here is the code snippet I'm working on within a component: import { Component, OnDestroy, OnInit } from '@angular/core'; import { interval, Subscription } from 'rxjs'; @Component({ selector: 'app-home', templateUrl ...