Converting a array of strings into an object with specific keys and values using Javascript

Within my code, I have a string that includes a series of personalized http headers in this particular arrangement:

var headers = "Referer=SomeValue|User-Agent=SomeUserAgent";

To break this down effectively, I utilized the pipe character as a separator:

var splitHeaders = headers.split("|");

Following this process, I obtained an array that can be iterated through. My goal is to transform this string array into an object. Here's what I've accomplished so far:

var customHeaders = {};
for (var i in splitHeaders) {
    var data = splitHeaders[i].split("=");
    customHeaders[data[0]] = data[1];
}

The idea is to construct an object named customHeaders to store values as shown below:

customHeaders = {
    "Referer":"https://someurl.com/",
    "User-Agent":"Some Browser"
};

Could there be any issue with the approach I'm taking?

Answer №1

You're headed in the right direction. Consider using a more conventional form of the for loop with the length of the splitHeaders array as the limiter:

for (var i = 0; i < splitHeaders.length; i++) {

Here's a practical example:

var headers = "Referer=SomeValue|User-Agent=SomeUserAgent";
var splitHeaders = headers.split('|');
var customHeaders = {};

for (var i = 0; i < splitHeaders.length; i++) {
  var data = splitHeaders[i].split("=");
  customHeaders[data[0]] = data[1];
}

console.log(customHeaders);


Alternatively, there are other techniques you can use to transform an array into an object, such as employing methods like reduce.

var headers = "Referer=SomeValue|User-Agent=SomeUserAgent";

headers = headers
  .split('|')
  .reduce(function(obj, val) {
    var split = val.split('=');
    obj[split[0]] = split[1];
    return obj;
  }, {});

console.log(headers);

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

Transfer the information from dropped files in a div to a separate page

document.getElementById('drag_drop').ondrop = function(event) { event.preventDefault(); var form_data = new FormData(); var drop_files = event.dataTransfer.files; for(var count = 0; count < drop_files.length; count++) ...

Error 19: Constraint violation - duplicate entry detected

While trying to set up my app, create a local database, and insert the very first user who has logged in locally, I encountered an error message at a specific point in the code. Here's where it happened: angular.module("greenApp") .service("d ...

Utilizing Angular 6's Mat-Table in a dynamic way

I am currently working on an Angular application that involves displaying data fetched from an API. The challenge I'm facing is that I do not have prior knowledge of the data I will be retrieving. Additionally, I need to create a model that can be use ...

Error in Firebase: The first argument provided to collection() must be a valid CollectionReference, DocumentReference, or FirebaseFirestore

Wow, this one has been quite a challenge for me. I had to go back to firebase9.4.0 in order to pinpoint where my code was causing errors. The error: https://i.sstatic.net/DLNPZ.png In a separate file named queries.config.js, I gather all the necessary su ...

What is the process of creating a dynamic array using the malloc function in the C programming language?

I am incorporating a dynamic array feature into my program utilizing the malloc function. There are 32 relays in total within my system, with a maximum of 12 relays being off at any given time, but in extreme cases, it could be all 32. For this reason, I ...

What is the purpose of the `Bitwise operator |` in the `d3.shuffle` source code and how can it be understood

Learning about the Bitwise operator | can be found in the document here and a helpful video tutorial here. However, understanding the purpose and significance of | may not come easily through basic examples in those resources. In my exploration of the sou ...

Delete an element from the state array using React

Users have the ability to input data through a form, which is then stored in an array called Acts within the state. When you click 'Start', the component handlePick is triggered. Following that, a 'NEXT' button appears which activates ...

The readFile function is not executing within a while loop

My goal is to send the updated contents of a text file over a socket connection using Express every time the file gets updated: console.log('Server running!'); var express = require('express'); var app = express(); var server = app.li ...

Node.js implementation for processing batches of data from the Youtube Data API

I'm looking to leverage the Youtube API for batch processing multiple video ids in a single request. Currently, I'm able to successfully make individual requests by appending the video id, request parameters, and API key to the following url: ? ...

Attention: React is unable to identify the X attribute on a DOM component

Encountering an error while attempting to pass props in a basic manner. interface Props extends Omit<React.HTMLAttributes<HTMLElement>, 'color'>, ChakraProps { handleMoveAll: () => void } export const MyWrapper: FC<Props> ...

Steps to obtain an array and utilize it in a datasource

Currently, I am facing a dilemma with an ajax call that retrieves an array: function test(){ $.ajax({ url: '/whatever/here'. data: data, }).done(function(newData){ var getArray = newData.SubData; newResult ...

Adjust the background color of the table header in Google Charts

Is it possible to dynamically change the background color of the header row (and rows) in Google Charts based on values from a PHP database? The documentation suggests using the following code: dataTable.setCell(22, 2, 15, 'Fifteen', {style: &a ...

Certain sections within a Formik form are failing to update as intended

I have successfully implemented a custom TextField wrapper for Material-UI fields, but I am facing an issue with native Material UI fields not updating the form data upon submission. Below is the relevant code snippet along with a link to a code sandbox d ...

The javascript dropdown feature functions properly on jsfiddle, but is not working in an HTML document

I am attempting to populate a dropdown menu with minutes using JavaScript. Although it works in this JSFiddle, the code does not function properly when I try to implement it on my own page. Below is the code snippet: <html> <head> ...

Eliminate redundant words in a map using React

{this.state.filterDataRows && this.state.filterDataRows.map((row, index) => { return row.cells.filter( val => { if(val.text.toLowerCase().includes(this.state.columnFilter.toLowerCase())){ return true } ...

Make the element switch from hidden to visible when hovering over it using CSS

I had a challenge to only show some rating text on my website when I hovered over it. Being new to coding with CSS and JavaScript, I was experimenting with overriding styles using the Stylebot extension in Chrome. I encountered an issue while trying to mo ...

Tips for fixing prettier errors in express and TypeScript code

I have set up a simple Node/Express + Typescript application app.listen(PORT, (): void => { console.log(`app is running in ${environment} and listening on port ${PORT}!`); }); I am encountering an error and I am unsure of the cause? Replace PORT, wit ...

What information is displayed on the visible class roster?

I'm feeling a bit lost with this. element.classList.add('visible'); Can someone clarify what the 'visible' in this code snippet is? Is it an event or something else? Appreciate your help! ...

The server encountered an unexpected error while processing the request, possibly due to a

My JavaScript file includes an interval function that calls the following code: setInterval(function() { $.getJSON('/home/trackUnreadMsgs', function(result) { $.each(result, function(i, field) { var temp = "#messby" + result[i].from; ...

Javascript regular expression fails to find a match

Is there a way to match all strings except for the ones containing '1AB'? I attempted it but it returned no matches. var text = "match1ABmatch match2ABmatch match3ABmatch"; var matches = text.match(/match(?!1AB)match/g); console.log(matches[0]+" ...