Reputation: 67
How do you convert this kind of KEY=VALUE format to an object?
Actual:
const text = "ID=40;KEY=TEST;FI=1010;SL=100"
Expected:
{
"ID": "40",
"KEY": "TEST",
"FI": "1010",
"SL": "100",
}
Is there an easy way to do this without hazzling too much with splits?
Upvotes: 0
Views: 61
Reputation: 9300
Here's my take on it using .reduce
yet also .split
:
const text = "ID=40;KEY=TEST;FI=1010;SL=100"
const output = text.split(";").reduce((o, key) => ({ ...o,
[key.split("=")[0]]: key.split("=")[1]
}), {})
console.log(output)
Upvotes: 1
Reputation: 1252
Use this utility method to handle the JSON string in the above format without using split()
const text = "ID=40;KEY=TEST;FI=1010;SL=100";
const jsonStringToObject = (string,keySeparator,objectSeparator) => {
const createJsonSeparator = (yourSeparator,standardSeparator) => {
return function(jsonString){
return jsonString.replaceAll(yourSeparator,standardSeparator);
};
};
const replaceForObjectSeparator = createJsonSeparator(objectSeparator,"\",\"");
const replaceForkeyValueSeparator = createJsonSeparator(keySeparator,"\":\"");
const jsonStart = "{\"";
const jsonEnd = "\"}";
return JSON.parse(jsonStart+replaceForkeyValueSeparator(replaceForObjectSeparator(text))+jsonEnd);
}
console.log(jsonStringToObject(text,'=',';'));
Upvotes: 0
Reputation: 370669
There's nothing wrong with using .split
here.
const text = "ID=40;KEY=TEST;FI=1010;SL=100"
const obj = Object.fromEntries(
text.split(';')
.map(substr => substr.split('='))
);
console.log(obj);
Upvotes: 5