javascriptarrayseventsource

construct array back together


My script reads EventSource, and on a message it will get some line data from a variable. That variable will be a array, my script breaks the array down and for each point it flips the x with the y value. It then sends each point as a post request. Is there anyway I can reconstruct the array back together, and then send the post request after flipping each x and y value?

here's my script:

  var evtSource = new EventSource("http://URL.com/");

evtSource.onmessage = function(e) {
var obj = JSON.parse(e.data);
var line = JSON.stringify(obj.line)
var line22 = obj.line


//console.log(line22)

line22.forEach(function(point, index){
console.log(JSON.stringify(point)); // console log example// -> "[120,250]"
    const [x, y] = point;

console.log(`x: ${x}, y: ${y}`);

    var FlipXYvalues = "[[" + y + "," + x + "]]"; // Complies it again... flips the values..


    var ident = "String"
if (obj.ident === ident) //the string...
{
$.post("http://URL.com/", {
            l: (FlipXYvalues),
            w : (obj.lineWidth),
            c: (obj.lineColor.replace("#", "")),
            o: ("100"),
            f: ("1"),
            _: ("false")
 })
}
});
}

Solution

  • You can use Array#map() to create a new array based on some other array

    line22 = [[1,2],[3,4],[5,6],[7,8]];
    var newLines = line22.map(point => {
      return [point[1], point[0]];
    });
    //using array destructuring
    //if you dont want to mess with specifying indexes
    var newLines = line22.map(([x,y]) => {
      return [y,x];
    });
    
    console.log(JSON.stringify(newLines));
    //$.post("http://URL.com/", {l:newLines});