【问题标题】:How to compare different objects of same json in Angular6 typescript?如何在Angular6打字稿中比较相同json的不同对象?
【发布时间】:2018-12-17 17:22:31
【问题描述】:

我有一个数组,如果使用 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 ]
     }];

【问题讨论】:

    标签: arrays json angular typescript


    【解决方案1】:

    使用以下代码:

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

    【讨论】:

    • 谢谢大家。我是打字稿的新手,这真的帮助了我:)
    【解决方案2】:

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

    【讨论】:

    • 是的,谢谢你的写作,但我自己想出了那部分:)
    猜你喜欢
    • 2021-10-23
    • 1970-01-01
    • 2020-01-09
    • 2020-02-18
    • 1970-01-01
    • 2017-09-23
    • 2019-09-29
    • 2014-11-09
    • 1970-01-01
    相关资源
    最近更新 更多