在JavaScript中,我有一个像
这样的字符串Package=sdvasd&Qty=1&Price=34?Package=sdabhjds&Qty=1&Price=234?
我想格式化像这样的对象数组
[
{'Package' : 'sdvasd', 'Qty' : 1, 'Price' : 34 }
{'Package' : 'sdabhjds', 'Qty' : 1, 'Price' : 234 }
]
我到目前为止所尝试的代码
let packageData = data.split('?');
let packageArr = [];
if( packageData.length > 0 ) {
for (var i = 0; i < packageData.length -1; i++) {
let str = packageData[i].split('&');
for (var j = 0; j < str.length; j++) {
let keys = str[j].split('=');
packageArr.push(keys[1])
}
}
}
console.log(packageArr);
但它并没有给我这样的结果。有人能告诉我如何使这个像所需的输出。任何建议和意见都会非常明显。 我只想要javascript方法而不是jQuery
答案 0 :(得分:1)
使用split
,map
和reduce
var output = str.split("?") //split by ?
.filter( s => !!s ) //filter out empty
.map( s => s.split( "&" ) //split by & and iterate each item
.reduce( (acc, c) =>
( t = c.split("="), acc[t[0]] = t[1], acc) //split each item by = and set each key to accumulator and return the accumulator
, {}) ); //initialize accumulator
<强>演示强>
var str = "Package=sdvasd&Qty=1&Price=34?Package=sdabhjds&Qty=1&Price=234?";
var output = str.split("?") //split by ?
.filter( s => !!s ) //filter out empty
.map( s => s.split( "&" ) //split by & and iterate each item
.reduce( (acc, c) =>
( t = c.split("="), acc[t[0]] = t[1], acc) //split each item by = and set each key to accumulator and return the accumulator
, {}) ); //initialize accumulator
console.log( output );
&#13;
答案 1 :(得分:0)
您可以拆分字符串并为外部拆分数组创建,并为内部拆分对象和最内部拆分键/值对。
var string = 'Package=sdvasd&Qty=1&Price=34?Package=sdabhjds&Qty=1&Price=234?',
result = string
.split('?')
.filter(Boolean)
.map(s => s.split('&').reduce((o, p) => {
var [k, v] = p.split('=');
return Object.assign(o, { [k]: v });
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:0)
你可以用它。您还可以检查number
值,以便qty
和Price
属性具有数值而不是字符串:
var str = 'Package=sdvasd&Qty=1&Price=34?Package=sdabhjds&Qty=1&Price=234';
var resArray = [];
str.split('?').filter((obj)=>{
var resObj = {};
obj.split('&').map((item)=>{
var itemSplit = item.split('=');
if(isNaN(itemSplit[1])){
resObj[itemSplit[0]] = itemSplit[1];
} else {
resObj[itemSplit[0]] = parseInt(itemSplit[1]);
}
});
resArray.push(resObj);
});
console.log(resArray);
&#13;
答案 3 :(得分:0)
尝试以下代码。创建一个对象,然后放入键值对。
let packageArr = [];
let packageDataArr = data.split('?');
Array.prototype.forEach.call(packageDataArr,(packageData)=>{
let dataObj = {};
let str = packageData.split('&');
Array.prototype.forEach.call(str,(keyValue)=>{
let keys = keyValue.split('=');
dataObj[key[0]] = key[1];
});
packageArr.push(dataObj);
});