Validating object values prior to adding a key

How can we add a new key-value pair called partnerCam to the res.items objects when partnerTermStart and partnerTermEnd are not null?

If partnerTermStart and partnerTermEnd have values, then we should insert a new key called partnerCam with a value calculated based on computeTermYears result.

Include partnerCam only if both partnerTermStart and partnerTermEnd are not null.

Is there a more efficient way to validate each object's partnerTermStart and partnerTermEnd before inserting the new key partnerCam? Thank you.

#my current code

 const newArr = res.items.map(v => ({...v, partnerCam: this.computeTermYears(new Date(v.partnerTermStart) , v.partnerTermEnd)}))

#function to insert computedDate

computeTermYears(startDate: Date, endDate: Date){
    let computedYears = null;
    if(startDate && endDate){
      const totalDays = AppUtils.Days360(startDate, endDate);
      computedYears =  totalDays / 360;
    }
    return this.partnerTerm = computedYears.toFixed(2);
  }

#sample object

[
    {
        "id": 248,
        "name": "248-A",
        "dealType": "Idle Buyout",
        "annualRentProposed": null,
        "annualRentCurrent": 349006.08,
        "firmTermRemainingCurrent": 17.666666,
        "maxAvailableTerm": null,
        "cashContribution": null,
        "cashFlow": 125535.65376980315,
        "description": null,
        "wagAnnualCurrent": 349006.08,
        "wagFirmTermRemainingCurrent": 17.666666,
        "partnerTermStart": "2021-10-28T00:00:00"
        "partnerTermEnd": "2021-10-28T00:00:00"
        "partnerCam": null,
  
    },
    {
        "id": 249,
        "name": "249-B",
        "dealType": "PM Restructure",
        "annualRentProposed": null,
        "annualRentCurrent": 349006.08,
        "firmTermRemainingCurrent": 17.666666,
        "maxAvailableTerm": null,
        "cashContribution": null,
        "cashFlow": 125535.65376980315,
        "description": null,
        "wagAnnualCurrent": 349006.08,
        "wagFirmTermRemainingCurrent": 17.666666,
        "partnerTermStart": null,
        "partnerTermEnd": null,
    },
    {
        "id": 258,
        "name": "251-D (copy)",
        "dealType": "Partner Location Submission",
        "annualRentProposed": null,
        "annualRentCurrent": 349006.08,
        "firmTermRemainingCurrent": 17.666666,
        "maxAvailableTerm": null,
        "cashContribution": null,
        "cashFlow": 125535.65376980315,
        "description": null,
        "wagAnnualCurrent": 349006.08,
        "wagFirmTermRemainingCurrent": 17.666666,
        "partnerTermStart": "2021-10-28T00:00:00",
        "partnerTermEnd": "2021-10-16T00:00:00",
        "partnerCam": 2323,
   
    }, 
]

Answer №1

If retaining copies of your objects is necessary, I would recommend using the following approach:

items.forEach(item => {
  if (item.partnerTermStart && item.partnerTermEnd) {
    item.partnerCam = this.calculateTermYears(new Date(item.partnerTermStart), item.partnerTermEnd);
  }
});

Example in Action

const items = [
    {
        "id": 248,
        "name": "248-A",
        "dealType": "Idle Buyout",
        "annualRentProposed": null,
        "annualRentCurrent": 349006.08,
        "firmTermRemainingCurrent": 17.666666,
        "maxAvailableTerm": null,
        "cashContribution": null,
        "cashFlow": 125535.65376980315,
        "description": null,
        "wagAnnualCurrent": 349006.08,
        "wagFirmTermRemainingCurrent": 17.666666,
        "partnerTermStart": "2021-10-28T00:00:00",
        "partnerTermEnd": "2021-10-28T00:00:00",
        "partnerCam": null,
  
    },
    {
        "id": 249,
        "name": "249-B",
        "dealType": "PM Restructure",
        "annualRentProposed": null,
        "annualRentCurrent": 349006.08,
        "firmTermRemainingCurrent": 17.666666,
        "maxAvailableTerm": null,
        "cashContribution": null,
        "cashFlow": 125535.65376980315,
        "description": null,
        "wagAnnualCurrent": 349006.08,
        "wagFirmTermRemainingCurrent": 17.666666,
        "partnerTermStart": null,
        "partnerTermEnd": null,
    },
    {
        "id": 258,
        "name": "251-D (copy)",
        "dealType": "Partner Location Submission",
        "annualRentProposed": null,
        "annualRentCurrent": 349006.08,
        "firmTermRemainingCurrent": 17.666666,
        "maxAvailableTerm": null,
        "cashContribution": null,
        "cashFlow": 125535.65376980315,
        "description": null,
        "wagAnnualCurrent": 349006.08,
        "wagFirmTermRemainingCurrent": 17.666666,
        "partnerTermStart": "2021-10-28T00:00:00",
        "partnerTermEnd": "2021-10-16T00:00:00",
        "partnerCam": 2323,
   
    }, 
];

function calculateTermYears(startDate, endDate) {
  let computedYears = null;
  if (startDate && endDate){
    const totalDays = 42;
    computedYears =  totalDays / 360;
  }
  return this.partnerTerm = computedYears.toFixed(2);
}

items.forEach(item => {
  if (item.partnerTermStart && item.partnerTermEnd) {
    item.partnerCam = this.calculateTermYears(new Date(item.partnerTermStart), item.partnerTermEnd);
  }
});

console.log(JSON.stringify(items, null, 2));

Answer №2

Here is an example of a basic Typescript function.

for( let item of res.items){
   if(item.partnerTermStart !== null && item.partnerTermEnd !== null) {

      // Perform necessary actions such as adding to an Array.
   }
}

Answer №3

Ensure that your map includes a check for both the starting and ending points. Additionally, within the computeTermYears function, instead of setting null, initialize computedYears as let computedYears = 0;.

const updatedArray = res.items.map(item => {
  if(item.partnerTermStart && item.partnerTermEnd){
    return {...item, partnerCam: this.computeTermYears(new Date(item.partnerTermStart) , new Date(item.partnerTermEnd))};
  }
  return item; 
);

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 to merge min and max validation errors when using React Hook Form?

<input {...register("subject", { maxLength: 50, minLength: 2, required: true, })} disabled={isLoading} id="subject" autoComplete=&q ...

Unlocking Security in Angular 2

I am struggling with the issue of security in Angular 2. I am attempting to calculate the width of a span element within an ngfor loop: <span style="width:updateStyle({{ ((date | amDifference : item.startdate : 'minutes' :true)/item.duratio ...

Utilizing the power of dojo/text! directly within a TypeScript class

I have encountered examples suggesting the possibility of achieving this, but my attempts have been unsuccessful. Working with Typescript 2.7.2 in our project where numerous extensions of dijit._Widget and dijit._TemplatedMixin are written in JavaScript, w ...

How can I limit generic types to only be a specific subtype of another generic type?

Looking to create a data type that represents changes in an object. For instance: const test: SomeType = { a: 1, b: "foo" }; const changing1: Changing<SomeType> = { obj: test, was: { a: test.a }, now: { a: 3 ...

What could be the reason behind the for loop not running within a typescript function?

My confusion lies in the for loop within this function that seems to never run. Each console log is set up to return a specific value, but the looping action doesn't trigger. Can someone provide insight into what might be causing this issue? export fu ...

Navigating from a library to app components: A step-by-step guide

I successfully converted my login-component into a library, and now the first thing displayed in myApp is the login page. However, I'm facing an issue with navigating to the home page after a successful login. Can anyone provide guidance on how I can ...

Issues with Angular Material Pagination functionality may be causing unexpected behavior

I'm facing an issue with displaying data in an HTML table using an API. I've tried to implement pagination to show 3 or 6 rows per page, but it's not working as expected. Currently, all the data is being displayed without any pagination, whe ...

Angular tutorial: Changing website language with translation features

Looking to translate my existing Russian website into another language using angular localization. Any recommendations on where I can find resources or tutorials for this? ...

Having trouble with your Angular CLI project after attempting to duplicate it by copy and paste?

As a newcomer to Angular, I've recently embarked on creating a new project using the Angular CLI. Everything was going well until I decided to upload my work to GIT. After copying and pasting the project folder contents into another directory, I encou ...

Angular does not display results when using InnerHtml

I'm currently in the process of creating a weather application with Angular, where I need to display different icons based on the weather data received. To achieve this functionality, I have developed a function that determines the appropriate icon to ...

How can you create an interface where the value type is determined by the key, but not all keys are predefined?

Below is an illustration of a data structure that I aim to define as a type in TypeScript: const dataExample = { Folder: { "Filename.js": { lines: { total: 100, covered: 80, ...

The onClick event in HostListener is intermittent in its functionality

While attempting to create a dropdown box in Angular by following these examples, I am encountering inconsistent results. Below is the code I have used: HTML <button (click)="eqLocationDrop()" id="eqLocButton"><i class="fas fa-caret-down">< ...

Creating a personalized stepper component (using custom icons) using HTML

Seeking guidance on how to achieve a design similar to the image below using HTML and CSS. After conducting extensive research, I have not been able to find a suitable solution. I attempted to modify this answer to fit my requirements, but it did not prod ...

The checkbox confirmation button appears to be absent in the ngx mat date time picker

I encountered a styling issue with the ngx mat datetime picker in my Angular 15 project. You can find the package here. To resolve the issue, I included @import "https://fonts.googleapis.com/icon?family=Material+Icons"; in my styles.scss file, and that re ...

The functionality of @Output and custom events appears to be malfunctioning

I am a beginner in Angular and attempting to pass data between child and parent components. In the child component.ts file: @Output() doubleClick = new EventEmitter<string>(); onDoubleClick(nameAccount: string){ this.doubleClick.emit(nameAccoun ...

Removing an object from an array when a certain key value already exists in TypeScript

I'm currently facing an issue with my function that adds objects to an array. The problem arises when a key value already exists in the array - it still gets added again, but I want it to only add if it doesn't exist yet. Here's what I have: ...

Tips for managing the output of an asynchronous function in TypeScript

The casesService function deals with handling an HTTP request and response to return a single object. However, due to its asynchronous nature, it currently returns an empty object (this.caseBook). My goal is for it to only return the object once it has b ...

next.js users may encounter a problem with react-table not rendering correctly

Encountering difficulties while attempting to integrate a basic table function into my upcoming application. Despite being a sample output, the function fails to load into the index for some unknown reason! // Layouts import Layout from "../components ...

Challenges with sorting and pagination in Angular 6's material-table

I am facing a challenge in my Angular6 material-data-table application where I need to display and manipulate a complex JSON structure received from a REST endpoint. While the data is successfully displayed, I am struggling to implement pagination and sort ...

Utilize the global theme feature within React Material-UI to create a cohesive

I'm feeling a bit lost when it comes to setting up React Material-UI theme. Even though I've tried to keep it simple, it's not working out for me as expected. Here is the code snippet I have: start.tsx const theme = createMuiTheme({ ...