javascriptxmlhttprequesteventsource

Extract values from array


Hello my script watches a stream...

On a message it will extract some data for me using a variable.

Here's the script:

  var evtSource = new EventSource("http://URL.com/_watch//_index?_=1557958948927");

evtSource.onmessage = function(e) {
var obj = JSON.parse(e.data);
var lineString = JSON.stringify(obj.line)
var size = JSON.stringify(obj.lineWidth)
var color = JSON.stringify(obj.lineColor) // Not needed, but defined anyways.
var chat = JSON.stringify(obj.msg)
var line = obj.line
console.log(line)

line.forEach(function(point, index){
     console.log(JSON.stringify(point)); // console log example// -> "[120,250]"
  });
}

in google's console it logs something like this [120,250]

How could I get each number, like the 120 as a variable, and the 250 as a different variable?

I tried something with the substr() method but it didn't work. It would somehow get the comma.


Solution

  • Just don't stringify the point array. Without stringifying you can destructure the array, like this:

    const [x, y] = point;
    

    or in a traditional way:

    const x = point[0];
    const y = point[1];
    

    both solutions are equal and produce the same output. Example:

    const point = [120, 250];
    
    const [x, y] = point;
    
    console.log(`x: ${x}, y: ${y}`);

    So your .forEach() could look like this:

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