简体   繁体   中英

How can I retrieve value from a string of list of map

I have some requirement like I need to get the values from a map actually where the format is as below:

"{xyz=True, abc=asd-1123, uvw=null}"

to get the values from this map which is in string.

I tried to use JSON.parse("{xyz=True, abc=asd-1123, uvw=null}") and also tried using var map = new Map(JSON.parse("{xyz=True, abc=asd-1123, uvw=null}"))

But neither way it was not working

well to start, json.parse is not going to work as that is not valid json. you are going to need to do the parsing yourself. So assuming everything is consistently in that method, you should start by stripping off the curly braces then breaking down your values and creating your map from those values.

So as an example:

let map = new Map(); // or create an object: {}, because you can get values using Object.values(yourObject)
let mapStr = "{xyz=True, abc=asd-1123, uvw=null}".slice(1, -1);
let kvp = mapStr.split(', ');
for(let i = 0; i < kvp.length; i++) {
   let splitVal = kvp[i].split(=);
   map.set(splitVal[0], splitVal[1]);
}

Then you can just use the map object you created.

Take into consideration this assumes none of your key-value-pairs have an "=" sign in them. you can also further investigate regexs to generate your maps. either way, it's on you to do the mapping unless there is a library that does this for you already in existence:)

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