javascript 将像 document.cookie 这样的字符串转换为对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5047346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:46:00  来源:igfitidea点击:

Converting strings like document.cookie to objects

javascriptarraysstringobject

提问by nyuszika7h

I have a string similiar to document.cookie:

我有一个类似于以下的字符串document.cookie

var str = 'foo=bar, baz=quux';

Converting it into an array is very easy:

将其转换为数组非常简单:

str = str.split(', ');
for (var i = 0; i < str.length; i++) {
    str[i].split('=');
}

It produces something like this:

它产生这样的东西:

[['foo', 'bar'], ['baz', 'quux']]

Converting to an object (which would be more appropriate in this case) is harder.

转换为对象(在这种情况下更合适)更难。

str = JSON.parse('{' + str.replace('=', ':') + '}');

This produces an object like this, which is invalid:

这会产生一个像这样的对象,这是无效的:

{foo: bar, baz: quux}

I want an object like this:

我想要一个这样的对象:

{'foo': 'bar', 'baz': 'quux'}

Note: I've used single quotes in my examples, but when posting your code, if you're using JSON.parse(), keep in your mind that it requires double quotes instead of single.

注意:我在示例中使用了单引号,但是在发布代码时,如果您使用的是JSON.parse(),请记住它需要双引号而不是单引号。



Update

更新

Thanks for everybody. Here's the function I'll use (for future reference):

谢谢大家。这是我将使用的函数(以供将来参考):

function str_obj(str) {
    str = str.split(', ');
    var result = {};
    for (var i = 0; i < str.length; i++) {
        var cur = str[i].split('=');
        result[cur[0]] = cur[1];
    }
    return result;
}

采纳答案by Nikita Rybak

Why exactly do you need JSON.parsein here? Modifying your arrays example

为什么你需要JSON.parse在这里?修改数组示例

str = str.split(', ');
var result = {};
for (var i = 0; i < str.length; i++) {
    var cur = str[i].split('=');
    result[cur[0]] = cur[1];
}

edit
An exampleto convince you.

编辑
一个例子来说服你。

回答by

The shortest way

最短的路

 document.cookie.split('; ').reduce((prev, current) => {
    const [name, value] = current.split('=');
    prev[name] = value;
    return prev
  }, {});

回答by sebilasse

note :The document.cookie (question headline) is semicolon separated and not comma separated (question) ...

注意:document.cookie(问题标题)以分号分隔,而不是逗号分隔(问题)...

An alternative using reduce:

另一种使用reduce

var str = 'foo=bar; baz=quux';
var obj = str.split(/[;] */).reduce(function(result, pairStr) {
  var arr = pairStr.split('=');
  if (arr.length === 2) { result[arr[0]] = arr[1]; }
  return result;
}, {});

回答by Alnitak

Given an array acontaining your intermediate form:

给定一个a包含中间形式的数组:

[['foo', 'bar'], ['baz', 'quux']]

then simply:

然后简单地:

var obj = {};
for (var i = 0; i < a.length; ++i) {
   var tmp = a[i];
   obj[tmp[0]] = tmp[1];
}

回答by ircmaxell

To convert it to an object, just do that from the beginning:

要将其转换为对象,只需从头开始:

var obj = {};
str = str.split(', ');
for (var i = 0; i < str.length; i++) {
    var tmp = str[i].split('=');
    obj[tmp[0]] = tmp[1];
}

Then, if you want JSON out of it:

然后,如果你想要 JSON 出来:

var jsonString = JSON.stringify(obj);

回答by Andy E

I'm a fan of John Resig's "Search and don't replace"method for this sort of thing:

我是 John Resig对此类事情的“搜索而不替换”方法的粉丝:

var str = 'foo=bar, baz=quux',
    arr = [],
    res = '{';

str.replace(/([^\s,=]+)=([^,]+)(?=,|$)/g, function (
var str = 'foo=bar, baz=quux',
    res = {};

str.replace(/([^\s,=]+)=([^,]+)(?=,|$)/g, function (
function stringToObject(str, delimiter) {
    var result = {};
    if (str && str.length > 0) {
        str = str.split(delimiter || ',');
        for (var i = 0; i < str.length; i++) {
            var cur = str[i].split('=');
            result[cur[0]] = cur[1];
        }
    }
    return result;
}
, key, value) { res[key] = value; }); console.log(res.foo); //-> "bar"
, key, value) { arr.push('"' + key + '":"' + value + '"'); }); res += arr.join(",") + "}"; alert(res);

Working example: http://jsfiddle.net/cm6MT/.

工作示例:http: //jsfiddle.net/cm6MT/

Makes things a lot simpler without the need for JSON support. Of course, it's just as easy to use the same regular expression with exec()or match().

无需 JSON 支持,事情就简单多了。当然,使用相同的正则表达式和exec()or一样容易match()



哎呀,我以为您想转换为 JSON 字符串,而不是对象。在这种情况下,您只需要稍微修改代码:

var text = 'foo=bar, baz=quux',
    pattern = new RegExp(/\b([^=,]+)=([^=,]+)\b/g),
    obj = {};

while (match = pattern.exec(text)) obj[match[1]] = match[2];

console.dir(obj);

Working example 2: http://jsfiddle.net/cm6MT/1/

工作示例 2:http: //jsfiddle.net/cm6MT/1/

回答by Neil Monroe

An alternate version of your updated solution that checks for the null/empty string and just returns an empty object and also allows for custom delimiters.

更新解决方案的替代版本,用于检查空/空字符串并只返回一个空对象,还允许自定义分隔符。

Object.fromEntries(new URLSearchParams(document.cookie.replace(/; /g, "&")))

回答by Joseph Merdrignac

parse cookies in a single line (IE9+):

在一行中解析 cookie (IE9+):

document.cookie.split('; ').reduce(function(result, v, i, a) { var k = v.split('='); result[k[0]] = k[1]; return result; }, {})

document.cookie.split('; ').reduce(function(result, v, i, a) { var k = v.split('='); result[k[0]] = k[1]; return result; }, {})

回答by Chad Scira

That's pretty crappy data, as long as its not using ,= this would work on that data

这是非常糟糕的数据,只要它不使用 ,= 这将适用于该数据

Object.fromEntries(new URLSearchParams(str.replace(/, /g, "&")))

回答by n4ly

URLSearchParams + Object.fromEntries

URLSearchParams + Object.fromEntries

for cookie

饼干

##代码##

your case

你的情况

##代码##

not recommend this if converted string can include special symbols

如果转换后的字符串可以包含特殊符号,则不建议这样做