简体   繁体   中英

Convert object property with string index notation to dot notation

I'm scratching my head a bit with this one. I have a URL as follows

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

When I get the query parameters using angularjs like so

var qs = $location.search();

I get an object like this

{ 
  SearchUnits: "km", 
  Postcode: "NG1 2AD", 
  "Position[south]": "53.9480673197085", 
  "Position[west]": "-1.1444808302915135", 
  "Position[north]": "52.9507652802915", 
  "Position[east]": "-1.1417828697085497" 
}

However I need it to look like this

{ 
  SearchUnits: "km", 
  Postcode: "NG1 2AD", 
  Position: { 
     south: "53.9480673197085", 
     west: "-1.1444808302915135", 
     north: "52.9507652802915", 
     east: "-1.1417828697085497"
  }
}

How do I go about parsing it? I have tried stringifying and then parsing but that doesn't work, any help would be appreciated

If the key values are static, then it's pretty easy to transform it, just iterate over an array of ['south', 'west', 'north', 'east'] and retrieve values/assign/delete as needed:

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

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