Reputation: 43973
If I have the string
PercentageValue = 99.9,\r\nCaseID = 9745683 PercentageValue = 90.3,\r\nCaseID = 9387593 PercentageValue = 88.6,\r\nCaseID = 4893448
How can I parse it into:
[
{PercentageValue : '99.9', CaseID : '9745683'},
{PercentageValue : '90.3', CaseID : '9387593'},
{PercentageValue : '88.6', CaseID : '4893448'}
]
There seems to be a space delimiter, but the issue is there are other spaces too.
Thanks
Upvotes: 0
Views: 85
Reputation: 4741
As shown by other answers, there are several ways to solve this. Here is an approach with .reduce()
:
var str = 'PercentageValue = 99.9,\r\nCaseID = 9745683 ' +
'PercentageValue = 90.3,\r\nCaseID = 9387593 ' +
'PercentageValue = 88.6,\r\nCaseID = 4893448';
console.log(
str
.split(/ = |,?\s+/)
.reduce(
function(c, v, i, a){
return i & 3 == 3 && (c[i >> 2] = {
PercentageValue: a[i - 2],
CaseID: v
}), c
}, []
)
)
Upvotes: 0
Reputation: 4370
var str = "PercentageValue = 99.9,\r\nCaseID = 9745683 PercentageValue = 90.3,\r\nCaseID = 9387593 PercentageValue = 88.6,\r\nCaseID = 4893448";
var parse = "["+str.replace(/(\w+)\s=\s(\d+(\.\d)?),\r\n(\w+)\s=\s(\d+)/g, "{\"$1\":\"$2\",\"$4\":$5}").replace(/\}\s\{/g, "},{")+"]";
console.log(JSON.parse(parse));
Upvotes: 1
Reputation: 506
var input = "PercentageValue = 99.9,\r\nCaseID = 9745683 PercentageValue = 90.3,\r\nCaseID = 9387593 PercentageValue = 88.6,\r\nCaseID = 4893448";
var res, resArray = [], re = /PercentageValue = (.*),\r\nCaseID = (\d*) ?/g;
while (res = re.exec(input))
resArray.push({PercentageValue: res[1], CaseID: res[2]})
Upvotes: 0
Reputation: 9998
var str = 'PercentageValue = 99.9,\r\nCaseID = 9745683 PercentageValue = 90.3,\r\nCaseID = 9387593 PercentageValue = 88.6,\r\nCaseID = 4893448';
var array = str.replace(/\r\n/g, '').replace(/\s=\s/g, ':').split(' ');
var objs = array.map((el) => {
return {
[el.split(',')[0].split(':')[0]]: el.split(',')[0].split(':')[1],
[el.split(',')[1].split(':')[0]]: el.split(',')[1].split(':')[1]
}
});
console.log(objs);
Upvotes: 1