代码之家  ›  专栏  ›  技术社区  ›  user27074

用字典中的单词替换数组中的单词

  •  3
  • user27074  · 技术社区  · 8 年前

    我有一个来自公共API的JSON输出,它返回代码而不是字符串。我能够将所需的字符串放入数组中,得到:

    OutNames = ["f1", "c2", "b3"]
    

    基于PDF,我想将代码翻译成单词,以便生成一个列表来显示。

    dictionary : any =  {"f1": "Baseball", "b3" : "Soccer" ,"c2": "Football"}
    

    我尝试了以下操作,但总是出错。

    this.OutNames = this.OutNames
    
          .map(function(each_element){
            each_element.replace(/[a-z]/gi, k => dictionary[k])});
    

    预期结果:

    Array = ["Baseball", "Football", "Soccer"]
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   Mark    8 年前

    你的想法是对的。您只需从返回字典查找 map() .无需致电 replace() 。 地图() 将返回一个新数组–如果需要,您可以覆盖旧值,但这里我只分配了一个不同的变量,以使其更清晰。

    OutNames = ["f1", "c2", "b3"]
    
    dictionary = {
      "f1": "Baseball",
      "b3": "Soccer",
      "c2": "Football"
    }
    let replaced = OutNames.map(el => dictionary[el])
    console.log(replaced)