简体   繁体   中英

Javascript: Parse string array into object with custom key names and values

So I have a string which contains a list of custom http headers that is in the following format:

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

I split that up using the pipe as a delimiter:

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

I'm left with an array which I can loop through, and I'm trying to convert that string array into an object. This is what I have so far:

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

What I'm essentially trying to create is an object called customHeaders to hold values like:

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

Am I doing something wrong?

You are on the right track. Use a more standard form of the for loop using the length of the splitHeaders as a limiter:

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

Working 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); 


There are also other methods you can use that allow you to convert an array of items into an object, using such as 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM