Reputation: 71
I have a database, with multiple cells, and under each cell, values.
Cells are: id, name, duration, date, and relationid
I have this code:
var result = {}
properties.data.forEach(addToResult); //Get data from database using properties.data
instance.data.datavarb = JSON.stringify(result); //Send data after converted to JSON
function addToResult(pair,isjson){ //operations
if(isjson===true) result[pair.key] = JSON.parse(pair.value); else result[pair.key] = pair.value;
}
I'm facing 2 problems:
1- First problem: This is how i get the value after converted to JSON:
{"id":"1","name":"Football","duration":"12","date":"02-07-2018","relationid":null}
How i need to be:
{id:1, name:"Football", duration:12, date:"02-07-2018", relationid:null}
Need remove the "" quotes from the numbers (id, duration and relationid) and the id,duration,relationid values.
2- Second problem: In the problem 1, just for show you I only was parsing one of the three values from my database. What happens when I parse them all? This is how it looks like:
{"id":"1, 2, 3","name":"Football, France, Belgium","duration":"12, 4, 3","date":"02-07-2018, 08-07-2018, 10-07-2018","relationid":", 1, 1"}
Instead of creating one by one, it creates the same identifiers (id,name,duration) and put all the values in the same. For my prupose i need to be:
{id:1, name:"Football", duration:12, date:"02-07-2018", relationid:null},
{id:2, name:"France", duration:4, date:"08-07-2018", relationid:1},
{id:3, name:"Belgium", duration:3, date:"10-07-2018", relationid:1}
Many thanks!!
Upvotes: 0
Views: 79
Reputation: 780871
You can test whether the values look like integers, and parse them.
function addToResult(pair,isjson){ //operations
if(isjson===true) {
result[pair.key] = JSON.parse(pair.value);
} else if (/^\d+$/.test(pair.value)) {
result[pair.key] = Number(pair.value);
} else {
result[pair.key] = pair.value;
}
}
Upvotes: 2