Rohit Mankotia
Rohit Mankotia

Reputation: 39

How to compare different objects of same json in Angular6 typescript?

I have an array in which i want to compare the object 'defaultvalue' and 'selectedvalue' in type script if there is a value in object 'higherOptions' using typescript.

let coverageArray = [
    {   
        "id":1, 
        "defaultValue": 100000,
        "selectedValue": 100000,
        "higherOptions": []
    },
    {
        "id":2,
        "defaultValue": 300000,
        "selectedValue": 300000,
         "higherOptions": [150000, 300000]
    },
    {
        "id":3, 
        "defaultValue": 500,
        "selectedValue": 500,
        "higherOptions": [500, 1000]
    },
    {
        "id":4, 
        "defaultValue": "ALS (12 months of restroration)",
        "selectedValue": "ALS (12 months of restroration)",
        "higherOptions": []
    },
    {
        "id":5,
        "defaultValue": 15000,
        "selectedValue": 15000,
        "higherOptions": [ 15000, 20000, 25000, 30000, 35000 ]
     }];

Upvotes: 1

Views: 77

Answers (2)

starfighter104
starfighter104

Reputation: 185

Rodrigo's answer is good but it's missing to check if the higherOptions array has a value.

Code:

let filteredCoverageArray = coverageArray
              .filter( coverage => coverage.higherOptions.length > 0
                                   && coverage.selectedValue === coverage.defaultValue);

Result:

 [  
   {  
      "id":2,
      "defaultValue":300000,
      "selectedValue":300000,
      "higherOptions":[  
         150000,
         300000
      ]
   },
   {  
      "id":3,
      "defaultValue":500,
      "selectedValue":500,
      "higherOptions":[  
         500,
         1000
      ]
   },
   {  
      "id":5,
      "defaultValue":15000,
      "selectedValue":15000,
      "higherOptions":[  
         15000,
         20000,
         25000,
         30000,
         35000
      ]
   }
]

Upvotes: 1

Rodrigo
Rodrigo

Reputation: 2503

Use the following code:

let filteredCoverageArray = coverageArray
      .filter( coverage => coverage.higherOptions.length
                           && coverage.selectedValue === coverage.defaultValue);

Upvotes: 1

Related Questions