Home > OS >  replacing value in an object if null in typescript
replacing value in an object if null in typescript

Time:10-13

how do we replace each key value if its null in a foreach ? every key value in an object if its null replace it with '-' ..

I have a sample basic example below , thanks.

#my sample code

res.items.forEach(v => {
              if(v === null) {
                v[v] = '-';
              }
              if(v.proposedTerm) {
                v.proposedTerm = Math.round(v.proposedTerm * 10) / 10    ' '   'years';
              }....

#sample object

[
    {
        "id": 499,
        "name": "118-A",
        "annualRentProposed": "$343,433",
        "annualRentCurrent": "$353,120.04",
        "firmTermRemainingCurrent": "10.8 years",
        "maxAvailableTerm": "10.6 years",
        "cashContribution": "$121,111",
        "cashFlow": "$543,834.54",
        "description": "adasdas",
        "wagAnnualCurrent": 353120.04,
        "wagFirmTermRemainingCurrent": 10.75,
        "partnerTermStart": null,
        "partnerTermEnd": null,
        "partnerCam": null,
        "partnerServiceFreeAndSecurityMonitoring": null,
        "proposedTerm": "23.2 years",
        "proposedMaxAvailableTerm": null,
        "partner": null,
        "partnerBaseRent": null,
        "createdOnString": "10/12/2021",
        "fileName": null,
        "serverFileName": null,
        "size": null,
        "absoluteUri": null,
        "sentTo": null
    }
]

CodePudding user response:

You need to iterate over the items array first and then iterate over each key of the object. You need nested forEach for this.

res.items can have multiple elements so run a forEach(). Now each of this element is an object with properties, so use Object.keys() to get the properties in an array. Check the value and replace

res.items.forEach(item => {
        Object.keys(item).forEach(x => {
              if(item[x] === null) {
                item[x] = '-';
              }
    ......
   }
}
  • Related