Exploring key value pairs dynamically in JavaScript

I have a JSON object containing HTTP request information:

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

Within this JSON, I need to access the headers and iterate through the array. The keys of the "headers" object are subject to change. I am seeking a method in Typescript/Javascript to retrieve both the keys and values from the headers in order to construct an HTTP call.

While many Stackoverflow articles provide solutions for accessing values using keys, I am specifically inquiring about how to handle both keys and values.

Although Object.getkeys() and Object.getValues() are available, they are not compatible with Safari. As a result, I am exploring alternative methods.

Answer №1

One useful feature is that Object.keys is supported in Safari browsers.

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

Answer №2

To avoid transpiling this code snippet, you can simply replace the let/const declarations with var. The template string used for the JSON could be replaced with actual API data during implementation, don't you think?

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(var i = 0; i < headers.length; ++i){
    for(var key in headers[i]){
      console.log(key, ":", headers[i][key])
    }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leverage the power of dynamic PHP variables within your JavaScript code

I have an image database and a search form. I want to display the images on the next page using JavaScript with the OpenLayers library. Here is the PHP code I wrote: <?php mysql_connect('localhost','root',""); mysql_select_ ...

Storing ng-change event for a checkbox in AngularJS in a valid manner

I have a requirement where I need to handle multiple input checkboxes. The goal is to store the changed checkbox events in an array and then save them when the user submits the changes. <td><input type="checkbox" class="switch" ng-model="each_val ...

Using AJAX to Send Requests to PHP

Embarking on my first ajax project, I believe I am close to resolving an issue but require some guidance. The webpage file below features an input field where users can enter their email address. Upon submission, the ajax doWork() function should trigger t ...

Utilize the asynchronous power of Morgan to quickly display your

After investing a considerable amount of time into this task, I'm uncertain about its feasibility: Creating a reverse lookup of IP addresses and logging it through morgan Express.use(Morgan(async(tokens, req, res) => { async function ip_reverse ...

Adjust the initial letter of every word with JQ Capitalization

I am currently working with a large JSON file using JQ to filter out unnecessary elements. While I have successfully achieved this, I encountered an issue with certain values being all capitalized strings. Unfortunately, JQ does not provide a built-in func ...

Leveraging Global Variables for Validation in Angular (Angular 10)

I am currently creating a form in Angular 10 which involves the use of validators. Specifically, I have been utilizing the Validators.min() method within my form... Instead of manually inputting the value '100' in the Validators.min('100&ap ...

Is there a way to signal an error within an Observable function that can handle multiple scenarios depending on the specific page being viewed in an Angular application?

Currently, I have a function called getElementList() which returns Observable<Element[]>. The goal is to handle different scenarios based on the user's current page - two cases for two specific pages and one error case. However, I am struggling ...

Using SCSS based on the browser language in Angular: A Step-by-Step Guide

Is there a way to implement SCSS that is dependent on the user's browser language? When I checked, I found the browser language specified in <html lang = "de"> and in the CSS code as html[Attributes Style] {-webkit-locale: "en&quo ...

The response you have received is delayed by one response

I seem to be facing an issue with my Node.js server where the response I receive is always delayed by one. The response I expect to get at the time of pressing the upload button is always received one step later. After starting the Node server, the initia ...

Renew The Dining Surface

I am looking for a way to update the table content without refreshing the entire page. I am using HTML, CSS, and JavaScript to display the current data from my sqlite3 database. Any tips on how to achieve this would be appreciated. ...

A step-by-step guide to setting up a custom splash screen for React Native

Looking for assistance in setting up a splash screen in react-native specifically for Android devices. I've managed to successfully implement one for iOS, but I'm encountering difficulties when it comes to getting one to work on Android. I' ...

What is the best way to use Jquery ScrollTo() to navigate to an element on a page using a class selector

Building on the information from this source, I have a question: How can I resolve the same issue using a class selector like $('.class')? I am encountering an error message that says Uncaught TypeError: undefined is not a function This occurs ...

The GET method is unable to process the body

I have been utilizing mockoon for creating API simulations. I set up 2 routes with the GET method, each responding with a JSON object. Interestingly, my express app seems to struggle parsing one of the routes. However, the route that includes an array in t ...

How can we incorporate methods using TypeScript?

I'm currently diving into TypeScript and encountering some challenges when trying to incorporate new methods into the DOM or other pre-existing objects. For instance, I'm attempting to implement a method that can be utilized to display colored te ...

Embed the picture into the wall

I recently constructed a wall using three.js and would like to add an image similar to the one shown in the example below. Since I am still new to three.js, I am seeking assistance with placing the image. Can anyone provide guidance on how to do this? ...

We encountered an issue: Headers cannot be set after they have been sent while attempting to read files

I encountered an error when attempting to read a file and send the response back to the browser. [ 'Error: Can\'t set headers after they are sent.', ' at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)&apo ...

Transform into specialized class by employing GSON and Generics with Kotlin in the XPLPC initiative

I am facing a seemingly simple problem in my project XPLPC. I'm having trouble converting from a generic class with reified using GSON and Kotlin. The specific error I am encountering can be found at: https://github.com/xplpc/xplpc/actions/runs/33958 ...

Click to open the file browser by using the onclick event in Material-table actions

Currently, I am working with a Material table component from "@material-table/core" My goal is to implement an action that enables users to upload a file within this table. I am facing some challenges on how to trigger the file browser when the ...

The specified argument type 'AsyncThunkAction<any, number | undefined, {}>' cannot be assigned to the parameter type 'AnyAction'

I'm currently working on a web application using the Next.js framework. Our tech stack includes Next.js, Redux, and Redux-Thunk. I encountered an error while coding, hence why I'm posting this question. The error message reads: 'Argument ...

In JavaScript, where are the values saved?

Can you clarify how JavaScript handles storage for primitive types and objects? Are primitive types always stored on the stack and objects on the heap, even within the scope of a function's execution? Also, are globally scoped variables and functions ...