我对此有点挠头。我的网址如下
http://localhost:50303/Directory?SearchUnits=km&Postcode=NG1%202AD&&Position[south]=53.9480673197085&Position[west]=-1.1444808302915135&Position[north]=52.9507652802915&Position[east]=-1.1417828697085497
当我像这样使用angularjs获取查询参数时
var qs = $location.search();
我得到了这样的物体
{
SearchUnits: "km",
Postcode: "NG1 2AD",
"Position[south]": "53.9480673197085",
"Position[west]": "-1.1444808302915135",
"Position[north]": "52.9507652802915",
"Position[east]": "-1.1417828697085497"
}
但是我需要它看起来像这样
{
SearchUnits: "km",
Postcode: "NG1 2AD",
Position: {
south: "53.9480673197085",
west: "-1.1444808302915135",
north: "52.9507652802915",
east: "-1.1417828697085497"
}
}
我该如何解析它?我尝试先进行字符串解析然后解析,但是那行不通,我们将不胜感激
答案 0 :(得分:1)
如果键值是静态的,则很容易对其进行转换,只需遍历['south', 'west', 'north', 'east']
数组并根据需要检索值/分配/删除:
const obj = {
SearchUnits: "km",
Postcode: "NG1 2AD",
"Position[south]": "53.9480673197085",
"Position[west]": "-1.1444808302915135",
"Position[north]": "52.9507652802915",
"Position[east]": "-1.1417828697085497"
};
const Position = {};
obj.Position = Position;
['south', 'west', 'north', 'east'].forEach((key) => {
const inputKey = `Position[${key}]`;
Position[key] = obj[inputKey];
delete obj[inputKey];
});
console.log(obj);