从URLSearchParams转换字符串数组值

时间:2018-12-20 02:03:23

标签: javascript javascript-objects

如何将字符串数组值转换为Javascript数组对象?

var querystring = 'lang[]=EN&lang[]=FR&type[]=1&type[]=2';

进入:

{
    lang: ['EN', 'FR'],
    type: ['2']
}

以下尝试:

let params = new URLSearchParams(decodeURI(querystring));
let entries = params.entries();

let result = {}
for(let entry of entries) { // each 'entry' is a [key, value]
    result[entry[0]] = entry[1];
}
return result;

这将导致:

[{
    "name": "lang[]",
    "value": "EN"
}, {
    "name": "lang[]",
    "value": "FR"
}, {
    "name": "type[]",
    "value": "2"
}]

3 个答案:

答案 0 :(得分:2)

this.state.matchedResults

答案 1 :(得分:2)

您可能应该测试[],以便您的代码不会以不以[]结尾的条目中断。然后,您可以将[]切成片,这样您的密钥就不会包含它:

var querystring = 'lang[]=EN&lang[]=FR&type[]=1&type[]=2&test=hello';

let params = new URLSearchParams(decodeURI(querystring));
let entries = params.entries();

let result = {}
for(let entry of entries) { // each 'entry' is a [key, value]
    let [key, val] = entry
    if (key.endsWith('[]')){         // array 
      key = key.slice(0,-2);         // clean up the key
      (result[key] || (result[key] = [])).push(val)
    } else {
      result[key] = val             // normal parameter
    }
}
console.log(result)

答案 2 :(得分:1)

最简单的版本是使用像qs这样的库

https://www.npmjs.com/package/qs#parsing-arrays

var withArray = qs.parse('a[]=b&a[]=c');

迷恋

a: ['b', 'c']