Reputation: 27
I will explain the main objective of my question.
I need to build a variable with this specific data structure:
date,value(line break)
2019-05-14 12:00:00,7.8
2019-05-15 00:00:00,14.5
2019-05-17 05:00:00,1
2019-05-19 20:00:00,2.3
2019-05-28 08:00:00,33.4
2019-05-28 10:00:00,18.8
2019-05-28 12:00:00,11.5
The purpose of this is to pass this variable with this exact structure to HighCharts as data input to create a Chart.
In order to retrieve and generate this data, I made a foor loop that reads a nested JSON array called "datos" (which contains an array with those values).
Below in the code you can see the values of "fecha"(date) and "valor"(value) variables.
for (var i = 0; i < datos.length; i++) {
var v = findPropPath(datos[i], 'v' );
var object = datos[i],
path = v,
getValue = (o, p) => p.split('.').reduce((r, k) => r[k], o);
var fecha = datos[i].data.time.s; // fecha = "2019-05-14 12:00:00"
var valor = getValue(object, path); // valor = "3.2"
var comma = ",";
var enter = "\n\r";
var datosF = fecha.concat(comma, valor, enter);
console.log(datosF);
};
As you can see, I tried to concatenate everything in a new variable called datosF.
Right now I'm stuck at this point because I don't know how to concatenate each line into a new variable that will contain all the lines inside as shown in the output example above.
At the moment, the console.log(datosF) gives the following:
I'm not even sure if my approach for the solution is valid, I'm a noob yet and can't find the proper solution yet.
Hope someone can help me with this.
Upvotes: 1
Views: 427
Reputation: 8937
Lots of ways to write this. With the least modification,
var datosF = ''
for (var i = 0; i < datos.length; i++) {
var v = findPropPath(datos[i], 'v' );
var object = datos[i],
path = v,
getValue = (o, p) => p.split('.').reduce((r, k) => r[k], o);
var fecha = datos[i].data.time.s; // fecha = "2019-05-14 12:00:00"
var valor = getValue(object, path); // valor = "3.2"
var comma = ",";
var enter = "\n\r";
datosF = datosF.concat(fetcha, comma, valor, enter);
};
console.log(datosF);
You have to save the result from each iteration into a variable from the outer scope.
There are a few bad practices going on here though. Such as creating a function in each iteration of the loop. Posting the original data will lead to the most concise solution.
Upvotes: 2