'valueTest', 'keyTest2'=>'valueTest2',..." to a Map object simply. I can do it with" /> 'valueTest', 'keyTest2'=>'valueTest2',..." to a Map object simply. I can do it with" /> 'valueTest', 'keyTest2'=>'valueTest2',..." to a Map object simply. I can do it with"/>

Convert a hstore into a Map object

85 Views Asked by At

I can't figure out to convert a string formatted like:

"'keyTest'=>'valueTest', 'keyTest2'=>'valueTest2',..."

to a Map object simply. I can do it with foreach but i wonder if there is a prettier way ?

I can do it like so :

let linksMap = new Map<string, string>();
family.links.split(',').forEach((element) => {
  const keyVal = element.split('=>');
  linksMap.set(keyVal[0], keyVal[1]);
});

Is there a way to cast directly or something like that ?

1

There are 1 best solutions below

0
Konrad On

You can use a Map constructor

const string = "'keyTest'=>'valueTest', 'keyTest2'=>'valueTest2'"

const map = new Map(string.split(',').map(item => item.trim().split('=>')))

console.log([...map])