user2655966 user2655966 - 2 months ago 12
TypeScript Question

Dynamically accessing the key value pair in Javascript

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.

Answer

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]]))
Comments