Javascript convert key value string to Object
Let the following "key value string":
"maxRU=5000;database=rktmb_credit;counting=databaseLevel"
I want that string to be converted to Objet or JSON:
{ maxRU: '5000', database: 'rktmb_credit', counting: 'databaseLevel' }
Use Object.fromEntries()
A built-in tool that is Use Object.fromEntries() where it states that:const arr = [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ];
const obj = Object.fromEntries(arr);
console.log(obj); // { 0: "a", 1: "b", 2: "c" }
So, the target is to get something like
[ ['0', 'a'], ['1', 'b'], ['2', 'c'] ];
From
"maxRU=5000;database=rktmb_credit;counting=databaseLevel"
In order to achieve that, we need a small utility:
const parseDescription = function (d) {
var a1 = d.split(";");
var r = a1.map(f => {return f.split("=");});
return r;
}
And this is how it executes in a Node REPL:
mihamina@a-onp ~]$ /home/mihamina/Apps/node/bin/node
Welcome to Node.js v16.17.0.
Type ".help" for more information.
> const parseDescription = function (d) {
... var a1 = d.split(";");
... var r = a1.map(f => {return f.split("=");});
... return r;
... }
undefined
> result=Object.fromEntries(parseDescription("maxRU=5000;database=rktmb_credit;counting=databaseLevel"));
{ maxRU: '5000', database: 'rktmb_credit', counting: 'databaseLevel' }
We got what we want.