【问题标题】:Match angular {{name}} with name in json array and get the corresponding data of that name from Json array将 angular {{name}} 与 json 数组中的名称匹配,并从 Json 数组中获取该名称的对应数据
【发布时间】:2021-02-03 11:39:38
【问题描述】:

所以我正在使用 angular,并且我有一个带有文本字段的警报框,它接受输入 ({{name}}) 并给出类似 Welcome {{name}} 的内容。我想将此 {{name}} 与具有名称和特定 ID 的 json 数组数据匹配。

我想要的是将 {{name}} 与 json 数组名称匹配并获取该名称的相应 id。并且只获取该 id 的最后 4 位数字。

JSON 数据:

var json=[{
name="bob",
id="FYW1985274"
},{
name="tom",
id="FYW1687647"
}]

JS

function xyz{
 var loginName = document.getElementById("login").value

  var search = json.map(d => d.name)

if(search.includes(loginName)){
  json[i].id // i should be index of matching name // I do not know how to get corresponding id with last 4 digits for that name.
} 
HTML
<welcome id="login" name="{{name}}"></welcome>

当我尝试使用 id="login" 获取名称时,它给了我完整的“欢迎名称”,但我只想要名称。

所以预期的输出应该是这样的

i/p: name="tom"
o/p: 7647

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript html angular


    【解决方案1】:

    您可以通过遍历数组并搜索名称来直接找到 id。 数组上的 find 方法在这里会很有用

    function xyz{
     var loginName = document.getElementById("login").value
    
      var id= json.find(user => user.name === loginName);
    
    // id now contains the id of the user whose name is entered in the input field
     console.log(id);
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-18
      • 2022-01-01
      • 2011-10-27
      • 2021-10-20
      • 2021-03-19
      • 2022-11-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多