-1

I have a JSON,

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

In this JSON, I need to access the headers and loop through the array. The keys of "headers" are dynamic. I need to access the keys as well as values. I need both keys and values to make a HTTP call. How can I do that in Typescript/Javascript

In all the Articles in Stackoverflow, I can able to see how to get the values using keys. Here I am asking how to retrieve keys as well as values.

I know that there is Object.getkeys() and Object.getValues() since these methods are not working in Safari, I am not choosing it.

arunan
  • 922
  • 1
  • 17
  • 25

2 Answers2

1

Object.keys is supported in safari.

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]]))
Alex
  • 14,104
  • 11
  • 54
  • 77
0

If you don't want to transpile this snippet you can easily switch the let/const declarations to var. I used a template string for the json, in practice you would probably get the value from some api, right?

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])
    }
  }
}
Pape
  • 291
  • 1
  • 9