循环遍历一组对象并找到一个特定的键

时间:2018-02-07 18:12:13

标签: javascript angular typescript

我有一个看起来像

的对象数组
data = 
[
  {
    "AccountType":"Client",
    "DeploymentList":
      {
        "-L3y8Kpl5rcvk-81q004":
        {
          "DeploymentKey":"-L3y8Kpl5rcvk-81q004",
          "DeploymentName":"Testing 3"
        }
      }
  },
  {
    "AccountType":"Client",
    "DeploymentList":
      {
        "-L3yGFxXQ8XbeK8b2GSF":
        {
          "DeploymentKey":"-L3yGFxXQ8XbeK8b2GSF",
          "DeploymentName":"Testing 1"

        }

      }
  }
]

我想循环浏览这些数据并希望找到一个字符串。在这个数据中,我想找到 enter image description here

到目前为止我尝试过的是

for (let d of this.data) {
      for(let a of d.DeploymentList){
        if(a.$key==="-L3y8Kpl5rcvk-81q004"){
          // Inside the condition
    }
}

但它不起作用。我怎么能做到这一点?

2 个答案:

答案 0 :(得分:2)

您可以按如下方式检查密钥是否存在,

for (let d of this.data) {
      for(let a of d.DeploymentList){
        if(a["-L3y8Kpl5rcvk-81q004"]){
          // Inside the condition
    }
}

答案 1 :(得分:0)

这取决于你想做什么。如果您只是尝试查找部署列表项,则可以使用find

轻松完成
var item = data.find(item => item.DeploymentList["-L3y8Kpl5rcvk-81q004"]);

这将为您提供data数组中包含该特定DeploymentList项的项目。



var data = 
[
  {
    "AccountType":"Client",
    "DeploymentList":
      {
        "-L3y8Kpl5rcvk-81q004":
        {
          "DeploymentKey":"-L3y8Kpl5rcvk-81q004",
          "DeploymentName":"Testing 3"
        }
      }
  },
  {
    "AccountType":"Client",
    "DeploymentList":
      {
        "-L3yGFxXQ8XbeK8b2GSF":
        {
          "DeploymentKey":"-L3yGFxXQ8XbeK8b2GSF",
          "DeploymentName":"Testing 1"

        }

      }
  }
];

var item = data.find(item => item.DeploymentList["-L3y8Kpl5rcvk-81q004"]);
console.log(item);