如何在Angular6打字稿中比较相同json的不同对象?

时间:2018-07-09 23:54:57

标签: arrays json angular typescript

我有一个数组,如果使用打字稿的对象“ higherOptions”中有值,我想在打字稿中比较对象“ defaultvalue”和“ selectedvalue”。

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 ]
     }];

2 个答案:

答案 0 :(得分:1)

使用以下代码:

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

答案 1 :(得分:1)

Rodrigo的回答很好,但缺少检查HigherOptions数组是否具有值的方法。

代码:

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

结果:

 [  
   {  
      "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
      ]
   }
]