【问题标题】:How to fetch matching values from a dictionary object in Typescript?如何从 Typescript 中的字典对象中获取匹配值?
【发布时间】:2020-04-27 21:31:52
【问题描述】:

我有一个字典对象,填充如下:

const myDictionaryElement = this.myDictionary["abc"];

这里,myDictionaryElement 具有以下值:

ACheckStatus: "PASS"
QVVStatus: "READY"
VVQStatus: "READY"
QTTStatus: "READY"
QBCTTStatus: "READY"
CStatus: "FAIL"

我想创建一个对象,这样所有的 key-value 对,其键与中间的 VV 匹配应存储在对象 valuesVV 中,如下所示:

const valuesVV = { QVVStatus: "READY" };

类似地,所有的 key-value 对,其中键与中间的 TT 匹配应存储在对象 valuesTT 中,如下所示:

const valuesTT = { QTTStatus: "READY", QBCTTStatus: "READY" } ;

并且所有的key-value 对,其中的键没有匹配的VVTT 在中间应该存储在对象valuesOther 中,如下所示:

const valuesOther = { ACheckStatus: "PASS", VVQStatus: "READY", CStatus: "FAIL"  } ;

为了实现 about 输出,我使用 hasOwnProperty 作为字典,但它不起作用

const valuesVV = myDictionaryElement.hasOwnProperty('*VV*');  // It is returning boolean false. The desired output is { QVVStatus: "READY" } 

【问题讨论】:

    标签: javascript node.js angular typescript dictionary


    【解决方案1】:

    您可以通过创建一个接受字典和匹配数组的函数来概括它,如下所示:

    const dict = {
      ACheckStatus: "PASS",
      QVVStatus: "READY",
      VVQStatus: "READY",
      QTTStatus: "READY",
      QBCTTStatus: "READY",
      CStatus: "FAIL"
    };
    
    const matching = ['VV', 'TT', 'SS'];
    
    function matchInput(input, matches) {
      // will have matched object in the index of the match and those without a match 
      // at the end
      const res = [];
    
      Object.keys(input).forEach(key => {
        // flag if the key wasn't matched to add it to no matches object
        let matched = false;
    
        matches.forEach((match, i) => {
          if (key.indexOf(match) > 0) {
            matched = true;
            if (!res[i]) res[i] = {};
            res[i][key] = input[key];
          }
        });
    
        if (!matched) {
          if (!res[matches.length]) res[matches.length] = {};
          res[matches.length][key] = input[key];
        }
      });
    
      return res;
    }
    

    想法是遍历每个键并将其插入正确的存储桶(对象)

    【讨论】:

      【解决方案2】:

      你应该过滤对象键并只选择你需要的那些,然后使用reduce创建一个新对象:

       const vvItems = Object.keys(dictElement)
        .filter(key => key.indexOf('VV')>= 1)
        .reduce((o, key) => { o[key] = dictElement[key]; return o; }, {})
      

      【讨论】:

      • 我认为这将包括{ QVVStatus: "READY" }VVQStatus: "READY" 但是,我只想要{ QVVStatus: "READY" }VV 位于中间的那个
      • @meallhour 您可以使用indexOf('VV') > 1,这样它将跳过以VV 开头的字符串。更新了答案
      • 在你的回答中,你有indexOf('VV') >= 1应该是indexOf('VV') > 1吗?
      • 它正在工作,我可以获取valuesVV valuesTT 的值但是如何在此处包含Not condition 以获取valuesOther 类似! (indexOf('VV') && ! (indexOf('TT')> 1) 的东西
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-19
      • 1970-01-01
      • 2016-07-22
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多