在Javascript中动态访问键值对

Dynamically accessing the key value pair in Javascript

本文关键字:访问 键值对 动态 Javascript      更新时间:2023-09-26

我有一个JSON

"http": {
    "method": "POST",
    "headers": [{
        "content-type": "application/json"
    }, {
        "Authorization": "KKYZASSHUYTRJ"
    }],
    "url": "http://localhost:8888/download/context"
}

在这个JSON中,我需要访问标题并通过数组循环。"headers"的键是动态的。我需要访问键和值。我需要键和值来进行HTTP调用。如何在Typescript/Javascript中实现

在Stackoverflow的所有文章中,我可以看到如何使用键获得值。这里我问的是如何检索键以及值。

我知道有Object.getkeys()和Object.getValues(),因为这些方法在Safari中不工作,我没有选择它。

对象。在safari中支持Keys

var data = {
    "http": {
        "method": "POST",
        "headers": [{"content-type": "application/json" },{ "Authorization": "KKYZASSHUYTRJ"}],
    "url": "http://localhost:8888/download/context"
    }
}

data["http"]["headers"].forEach(entry => console.log(Object.keys(entry)[0], entry[Object.keys(entry)[0]]))

如果你不想编译这个代码片段,你可以很容易地将let/const声明转换为var.我使用了一个模板字符串作为json,在实践中你可能会从一些api获得值,对吗?

var json = JSON.parse(`
{
  "http": {
    "method": "POST",
    "headers": [{
        "content-type": "application/json"
    }, {
        "Authorization": "KKYZASSHUYTRJ"
    }],
    "url": "http://localhost:8888/download/context"
  }
}`);
if(typeof json.http !== "undefined" && typeof json.http["headers"] !== "undefined"){
  const headers = json.http["headers"];
  for(let i = 0; i < headers.length; ++i){
    for(let key in headers[i]){
      console.log(key, ":", headers[i][key])
    }
  }
}