Create a conditional statement based on the properties of an object

In one of my Typescript projects, I am faced with the task of constructing a dynamic 'if' statement based on the data received from an object. The number of conditions in this 'if' statement should match the number of properties present in the object.

Here is the initial object:

interface EmailParams { 
  sender?: string,
  subject?: string,
  fileType?: string
}

let params: EmailParams = {
  sender: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="720617010632151f131b1e5c111d1f">[email protected]</a>"
}

This is the condition that needs to be met:

if (test1.from.toUpperCase() == params.sender?.toUpperCase())

If there are changes made to the object, here is the updated version:

interface EmailParams { 
  sender?: string,
  subject?: string,
  fileType?: string
}

let params: EmailParams = {
  sender: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c38293f380c2b212d2520622f2321">[email protected]</a>",
  subject: "data"
}

The new 'if' statement should now look like this:

if (test1.from.toUpperCase() == params.sender?.toUpperCase() &&
    test1.data.toUpperCase() == params.subject?.toUpperCase()
)

Answer №1

To achieve this, a common approach is to follow these steps:

const properties: (keyof EmailParams)[] = [
  'sender',
  'subject',
];

const sampleData = {
  data: "whatever",
  from: "foobar",
};

const mapping: {
  [k in keyof EmailParams]: keyof typeof sampleData
} = {
  subject: 'data',
  sender: 'from',
}

const compareEmailParams = (obj: EmailParams): boolean => {
  return properties.every((k: keyof EmailParams) => {
    if (k in mapping) {
      const key: keyof typeof sampleData = mapping[k] as keyof typeof sampleData;
      return obj[k]?.toUpperCase() === sampleData[key].toUpperCase();
    }
    return true; 
  });
};

console.log(compareEmailParams(params));

If you need to add a new property, remember to update the list of keys and the mapping between email params and sample data.

This approach offers several advantages, such as easier unit testing without relying on conditional logic and the ability to reuse the function in different parts of the codebase.

Playground

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

Having trouble retrieving data from redux toolkit using typescript

I've been diving into the world of Typescript by building a simple todo app using React, Redux-toolkit, and Typescript. One issue I encountered is when trying to access data from the store with useSelector. The retrieved object contains the desired va ...

convert a JSON object to an array using jQuery

Can anyone help me with converting an object into an array using jQuery? [["20"],["30"],["45"],["54"],["33"],["15"],["54"],["41"]] I am looking to achieve an array output like this: [20,30,45,54,33,15,54,41] Any suggestions on how to accomplish this? ...

Updating array with user input using Ajax

For the past few days, I have been struggling to extract data from a PHP page (array) and store this data in a jQuery array. The issue arises when trying to send data to the PHP page using the following code: $.ajax({ type: "POST", url: 'test ...

Deploying AWS CDK in a CodePipeline and CodeBuild workflow

I am currently attempting to deploy an AWS CDK application on AWS CodePipeline using CodeBuild actions. While the build and deploy processes run smoothly locally (as expected), encountering an issue when running on CodeBuild where the cdk command fails w ...

Accessing an array outside of an Ajax call that was initiated within a success callback

I have a CSV parsing function written in JavaScript that extracts movie names from a CSV file using an Ajax call within a loop. movies = new Array(); for (var i = 1; i < allData.length; i++) { var mName = allData[i][0]; var mPath = allData[i ...

There seems to be an issue with the Angular zone.js and zone-evergreen.js files showing an error that reads:

My Angular 11 app suddenly started showing errors across all browsers and environments (local, staging, prod) about an hour ago without any updates: Uncaught TypeError: t.getElementsByTagName is not a function at computeStackTrace.js:338 at Array.f ...

Learn the process of importing data types from the Firebase Admin Node.js SDK

I am currently facing a challenge with importing the DecodedIDToken type from the https://firebase.google.com/docs/reference/admin/node/firebase-admin.auth.decodedidtoken. I need this type to be able to assign it to the value in the .then() callback when v ...

Exploring the best practices for integrating Bootstrap into a Webpack and Angular2 project

I am looking to incorporate Bootstrap into my Angular2 project, including both the CSS and JS files. What is the best way to include these files in the project to ensure webpack functions properly? In the previous version using systemjs, it was included i ...

Alias destructuring for arrays within nested objects

I'm currently attempting to change the names of certain objects from one array (eventFetch) and transfer them into another array (mapEvents). I initially tried using destructuring aliases for this task, but since I need to rename a nested object, it d ...

Ensuring a Generic Type in Typescript is a Subset of JSON: Best Practices

I am interested in achieving the following: interface IJSON { [key: string]: string | number | boolean | IJSON | string[] | number[] | boolean[] | IJSON[]; } function iAcceptOnlyJSON<T subsetof IJSON>(json: T): T { return json; ...

Retrieve data from an HTML form within an Angular 2 ag-grid component

I'm facing a challenge with incorporating form values from a modal into an ag-grid array in my HTML file. I'm unsure of the process to achieve this. Below is an excerpt from my file.html: <template #addTrainContent let-c="close" let-d="dismi ...

Is it possible to use the `fill` method to assign a value of type 'number' to a variable of type 'never'?

interface Itype { type: number; name?: string; } function makeEqualArrays(arr1: Itype[], arr2: Itype[]): void { arr2 = arr2.concat([].fill({ type: 2 }, len1 - len2)); } What is the reason for not being able to fill an array with an ob ...

Issue with Jest/SuperTest Express integration tests: encountering "Can't set headers after they are sent" error when making requests to the same endpoint in multiple test cases

Dealing with a tricky situation here.. I'm currently in the process of writing integration tests for an Express (Typescript) app, using Jest and Supertest. My challenge lies in having multiple tests for the same endpoint, specifically to test respon ...

The transition() function in Angular 2.1.0 is malfunctioning

I am struggling to implement animations in my Angular 2 application. I attempted to use an example I found online and did some research, but unfortunately, I have not been successful. Can anyone please assist me? import {Component, trigger, state, anima ...

Issue: Troubleshooting data serialization process using getStaticProps in Next.js

I attempted to retrieve data from an API, but unfortunately encountered the following error: Server Error Error: Issue with serializing .results returned from getServerSideProps in "/". Reason: JSON serialization does not support undefin ...

Using the moment library in Angular to convert date and time can sometimes lead to errors

Whenever I attempt to convert a Gregorian date to a Persian date, the minute value in the conversion ends up becoming an error. For instance, let's say I want to convert this specific date and time to a Persian date: 2020-09-14T16:51:00+04:30 should ...

The custom component is not updating the NgIf directive in HTML even though it receives a boolean variable

I am struggling with a custom component that includes an *ngIf in its view to handle a boolean variable, but for some reason the *ngIf directive is not working. Here is the code snippet: Component @Input('title') titleText; @Input('backButt ...

Encountering Typescript issues following the transition from npm to pnpm

Currently, I am facing a challenge in migrating an outdated Angular JS project from npm to pnpm. The main issue I am encountering is related to typescript errors, particularly the error message that states: error TS2339: Property 'mock' does not ...

The outcome of a function within the $.ajax method is transformed into a string

Trying to pass an array of IDs using the $.ajax data variable is proving to be a challenge. The array is generated by a function, and I've noticed that if I define this function outside of the $.ajax call, it works fine. However, when I place the same ...

Combine several objects into one consolidated object

Is there a way to combine multiple Json objects into one single object? When parsing an array from AJAX, I noticed that it logs like this: 0:{id: "24", user: "Joe", pass: "pass", name: "Joe Bloggs", role: "Technical Support", ...} 1:{id: "25", user: "Jim ...