I receive in the backend (nodejs) a string with this format:
t0=16,21,32,8$t1=15,33,46,4$t2=26,27,37,5$t3=9,29,40,8
I need to convert it to a JSON object with this format:
{"bets":[
{"n1":16, "n2":21, "n3":32,"s1":8 },
{"n1":15, "n2":33, "n3":46,"s1":4 },
{"n1":26, "n2":27, "n3":37,"s1":5 },
{"n1":9, "n2":29, "n3":40,"s1":8 }
]}
The real thing is that i have no clue on how to achieve this...
split
method of Strings allows you to "split" a string by a delimiter into an array. Take this example:
'1,2,3'.split(','); // => [1,2,3]
Answer to your question using split
:
var string = 't0=16,21,32,8$t1=15,33,46,4$t2=26,27,37,5$t3=9,29,40,8';
var obj = {
bets: []
};
string.split('$').forEach(function(x) {
var o = {n1: '', n2: '', n3: '', s1: ''};
x.split(',').forEach(function(y, index) {
o[index < 3 ? 'n' + (index+1) : 's1'] = index == 0 ? +y.slice(3) : +y;
});
obj.bets.push(o);
})
Lemme explain the code, it might seem complex at first.
First we split the string by $
, the delimiter of our yet-to-be-bets, then we split each part by ,
in order to get our numbers out.
Now what's happening at [index < 3 ? 'n' + (index+1) : 's1']
?
This is an inline if/else statement, if you're not familiar with them, take a look at this.
What it does is: check if we're at the third element of our array, if yes, set the key to s1
, else, the key will be 'n' + (index+1)
which will result in n1
at 0 index and so on.
We have another inline if statement in our value, what's that? Our first element will not be just a number, it will be something like t0=16
, but we only need the number, so we check if we're at the first element, if so, slice up the string.
The +y
converts our string to integer/float, it's similar to calling parseInt()
with a few small differences.
You could achieve this by using split and reduce:
var data = 't0=16,21,32,8$t1=15,33,46,4$t2=26,27,37,5$t3=9,29,40,8'.split('$');
var result = data.reduce(function (mem, curr) {
var d = curr.split(',');
mem.bets.push({
"n1": +d[0].replace(/t\d+=/, ''),
"n2": +d[1],
"n3": +d[2],
"n4": +d[3]
});
return mem;
}, {"bets": []});
Using a combination of String.prototype.split()
and some basic regex
var input = 't0=16,21,32,8$t1=15,33,46,4$t2=26,27,37,5$t3=9,29,40,8';
var objs = input.split('$');
var result = { bets: [] };
var re = /^t[0-9]+=([0-9]+),([0-9]+),([0-9]+),([0-9]+)$/i;
for (var i in objs) {
var matches = re.exec(objs[i]);
result.bets.push({
"n1": matches[1],
"n2": matches[2],
"n3": matches[3],
"s1": matches[4]
});
}
console.log(result);