How to sort an object dynamically

Hello i have the following JSON object


This is created by the following code :

$( document ).ready( function(){
    $.ajax({
        type: 'GET',
        url: 'DonneesGraph.php?Base='+jsvar,
        dataType: 'json',
        success: function( retour ) {
			// Ici le traitement des données retournées placé dans quelquechose=JSON ? appelé retour 
            
			console.log( "retour" , retour );

And then i have sorted this with following code witch is working :

let newArray4 = retour.map((d) => ({ date: timeConv(d.MoyDate), measurement: +d.ProductionPV}));
let newArray6 = retour.map((d) => ({ date: timeConv(d.MoyDate), measurement: +d.EauDepart }));
let newArray7 = retour.map((d) => ({ date: timeConv(d.MoyDate), measurement: +d.EauRetour }));

Now i am trying to do it dynamically with the following :

while(i <= Lenght)
{	
if (typeof Nom[i] !== 'undefined') //Test si array présent et défini et initialisé
{
  console.log('Içi',Nom[i]);// Nom[i] is defined AND initialized
  var NomCourbe = Nom[i];
  var NomArray = 'newArray'+[i];
  var testing = 'd.EauRetour';
  console.log('Nom de la courbe',NomCourbe);
  console.log('Nom de l array',NomArray);
  console.log('Colonne',C2);
 newArray[i] = retour.map((d) => ({ date: timeConv(d.MoyDate), measurement: +Nom[i] }));
  i++;
} else 
{
	console.log('Là',i);
	i++;}
}

But this is not working.The console.log is showing newArray1 undefined.
I have tried different things as :

newArray1 = retour.map((d) => ({ date: timeConv(d.MoyDate), measurement: +testing }));
or 
NomArray = retour.map((d) => ({ date: timeConv(d.MoyDate), measurement: +testing }));

But nothing works if someone can explain me why ? Thanks

Sorry but this is sorting nothing….

What do you mean with sort?

For sorting you should use (surprise, surprise)

array.sort()

I… think we’re a few steps away from the complexities of a sort, as the OP is stumped by variable instantiation at the moment.

There’s a lot going on in what you pasted, not least of which being your misspelling of length, but let’s… stick to the initial problem you asked about for now…

newArray doesnt exist because you havent told it to exist. At least, nowhere you’ve shown us do you define newArray.

Before all your while’ing and that if statement that… doesnt really make a lot of sense to me because your array of objects appears to not be sparse and… right. Initial problem. Baby steps.

let newArray = [];

Ok i use the word ‘sort’ as litteral english meaning, i don’t know how to say that but mapping the JSON object with the instruction map to exctract the data i need :wink:

Ok i didn’t post all the code to didn’t disturb the understanding. So here are the top of the code.

let newArray1;
let newArray = [];
var i=1;

What i take it from your code… is that you’d like to take the elements of one array, Nom, and combine it with it with the objects in your existing array, retour, such that you end up with an array of objects consisting of the timeConv’d date from the first object, and the value from Nom in the measurement value.

I assume, from your need to if the whole thing, that the Nom array is sparse - in other words, it has holes in it.
The short form of what you appear to be trying to do is:

let newArray = Nom.map((x,i) => {date: timeConv(retour[i].MoyDate), measurement: x});

(note that this assumes that retour is bigger than or equal to the size of Nom)

Ok i think you get the point witch is not easy to explain…so if you look on the Object in picture, there is the date,EauAller,EauRetour,ProductionPV. So i want to create 3 arrays like this Array1 : Date,EauAller then Array2 : Date,EauRetour and Array3 : Date,ProductionPV. But this can by from one array to 5 or more array depending on the original JSON that i get from a Sql request.
Formated like this
{
“date”: “2022-07-23T15:08:30.000Z”,
“measurement”: 3400
}

I mean, I question why you need to do this, instead of just passing the whole thing around, but sure…

What… part of this is ‘dynamic’, exactly?

Ok i see you need tu understand what is Nom :

const Nom=Object.keys(retour[0]);

Witch give me how much loop i should do by looking if this ‘key’ is define here :sweat_smile:

if (typeof Nom[i] !== 'undefined')

Why, because i get a code witch is working with formted data like this and i just learned Javascript few month ago started so i try to adapt existing code to do what i need. The target is to get this number of array and then to draw some curve.

By Dynamic, i mean that actually i have to adapt the code depending on with graphique line i want to draw into this code :

let newArray1 = retour.map((d) => ({ date: timeConv(d.MoyDate), measurement: +d.EauDepart }));
let newArray2 = retour.map((d) => ({ date: timeConv(d.MoyDate), measurement: +d.EauRetour }));
let newArray3 = retour.map((d) => ({ date: timeConv(d.MoyDate), measurement: +d.ProductionPV }));
//let newArray4 = retour.map((d) => ({ date: timeConv(d.MoyDate), measurement: +d.ProductionPV }));
//let newArray5 = retour.map((d) => ({ date: timeConv(d.MoyDate), measurement: +d.ConsommationElec }));
//let newArray6 = retour.map((d) => ({ date: timeConv(d.MoyDate), measurement: +d.EauDepart }));
//let newArray7 = retour.map((d) => ({ date: timeConv(d.MoyDate), measurement: +d.EauRetour }));
//let newArray8 = retour.map((d) => ({ date: timeConv(d.MoyDate), measurement: +d.IntensitePAC }));
//let newArray9 = retour.map((d) => ({ date: timeConv(d.MoyDate), measurement: +d.ResistancePAC }));
//let newArray10 = retour.map((d) => ({ date: timeConv(d.MoyDate), measurement: +d.Humidite }));

But now that i can extract the name from the JSON, i want to create this different array with the result of Nom[i] witch gives me how many different curve i have to draw

OH. I see. You’re trying to iterate over an unknown or changing object shape. I got you now.

So… the… easiest way I can think of to do this is an object of arrays of objects. (Confused yet? Cool.)

let output = {}; //Empty Object to start with.
Object.keys(retour[0]).forEach(key => { //Walk the keys of the object.
  if(key == "MoyDate") { return; } //Skip doing the date. Cause we're gonna put the date everywhere.
  output[key] = retour.map((x) => { return {"date": timeConv(x.MoyDate) , "measurement": Number(x[key])}});
});

You think that it’s cool :hot_face: Hot stuff for me. So now it’s really late so i need to go to bed. But i think that your answer is matching my expectation. I will try this later now. Thanks a lot for your time helping me to understand my point. I get a lot of trouble to understand this story of array and object and array of object and playing with this multidimensions…Thanks

1 Like

@m_hutley Wonderfull, i get it working and this is doing almost what i need. I still need some improvement on the output. Actually with your code i get result like this :


But i would like to have it like this :

So i have tryed this :

var i=-1;

//Bloc essais Splice avant map
//enleves = retour.splice(1,1, []);
//console.log('enleves',enleves);
//comb.splice(i,1, []);
let output = {}; //Empty Object to start with.
Object.keys(retour[0]).forEach(key => { //Walk the keys of the object.
  if(key == "MoyDate") { return; } //Skip doing the date. Cause we're gonna put the date everywhere.
  output[i++] = retour.map((x) => { return {"date": timeConv(x.MoyDate) , "measurement": Number(x[key])}});
});
console.log('Output',output);

Witch come closer to my request but i don’t understand why the 3rd array created become -1 ??? and how to code it with the id and values ?

Thanks

Right, lets handle the two separate parts of this:

Why is this array key -1?

it didnt. The first array you created became -1.

So i is -1.

because you’ve put the ++ after the variable, this will return the CURRENT value, then do the addition.

var i = 0;
console.log(i++); //Logs 0, then sets i to 1.
console.log(i++); //Logs 1, then sets i to 2.

If you had put the ++ first, it would do the addition first, then return the value:

var i = 0;
console.log(++i); //Sets i to 1, then logs 1.
console.log(++i); //Sets i to 2, then logs 2.

So when you tell i to be -1, and then run this line:
output[i++] = retour.map((x) => { return {"date": timeConv(x.MoyDate) , "measurement": Number(x[key])}});

Javascript will set output[-1], and then set i to 0.

Output not desired format.

You’re close to what you want.
What I gave you was an object that contains arrays of objects.
What you have stated you want is an array of objects, which has a property that is an array of objects. (Yup, that sentence is as confusing as it sounds.)

let Slices = []; //start with an empty array.
Object.keys(retour[0]).forEach(key => { //Walk the keys of the object.
  if(key == "MoyDate") { return; } //Skip doing the date. Cause we're gonna put the date everywhere.
//So we want each of these results to be an object, with an id, and values.
//This line is going to be rather long and full of symbols. I suggest looking at this in a bracket-matching IDE to be able
//to keep track of all those close brackets and parentheses at the end there.
  Slices.push({ "id": key, "values" : retour.map((x) => { return {"date": timeConv(x.MoyDate) , "measurement": Number(x[key])}}) });
});
1 Like

Thanks a lot to be so fast and for your help. I will test it when i have time (Because i am at work :wink: ) Then i think i will be able to put this as solved :slight_smile: And yes the manipulation of object, array and all mixed togethere make me reallt crazy, very difficult to understand but i learn a little forward each time. Thx for your support.

1 Like

@m_hutley Hi, so now i get everything i need. One more time i would like to thanks you a lot for your help. I have just a last question because now in the console.log i have this message :

[Violation]‘load’ handler took 584ms jquery.min.js:4

So it seems that this is in relation with the traitement on some instruction witch takes too much time, for me i don’t really care but i just want to be sure that this is something that should be solved or i can live it like this ?

I wouldnt particularly consider a load handler taking half a second to be fatal. The load handler only runs once.

Oki Doki this was what i was thinking. Thanks i will pass this topic as solved :slight_smile: :+1:

I would never ignore any warning….