We are receiving an input parameter value as a pipe-delimited key-value pair, separated with =
symbols. For example:
"|User=0101|Name=ImNewUser|IsAdmin=0|RefId=23ae2123cd223bf235|"
So the format is: |KEY=VALUE|KEY_2=VALUE_2|....|KEY_n=VALUE_n|
I need to split it into a JSON object. So, my object should be :
{
'User':'0101',
'Name':'ImNewUser',
'IsAdmin':'0',
'RefId'='23ae2123cd223bf235'
}
What will be best way to go, since there are multiple options:
|
and again on each element split with =
.=
remove trailing |
symbol and associate two
different arrays with indexes.Can anyone tell me the best/most efficient way of doing this in JavaScript (programming in Node.js)?
The first one sounds good:
var str = "|User=0101|Name=ImNewUser|IsAdmin=0|RefId=23ae2123cd223bf235|";
var result = {};
str.split('|').forEach(function(x){
var arr = x.split('=');
arr[1] && (result[arr[0]] = arr[1]);
});
If you do decide to use regex, make sure it's block rockin' regex like this:
var result = {};
s.replace(/([^=|]+)=([^|]*)/g, function(noStep3, a, b) { result[a] = b; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With