Toni Au Toni Au - 4 years ago 76
Javascript Question

Read text file line by line and use data for input

I am reading in a text file where I know what each line of the file is.

For example, the first line is a starting coordinate pair that is in the format {"x":9,"y":9} and the second line is a end coordinate pair.

There exists global variable

var startCoord = {"x": startX, "y": startY};


How can I pull the x and y from the file to set as the new
startCoord.x
and
startCoord.y
respectively?

JSFiddle here

Example of text file:

{"x":9,"y":9}
{"x":4,"y":104}
{"x":124,"y":51}
{"x":92,"y":65}
{"x":113,"y":31}

Answer Source

You need to parse the JSON in each line into an object in order to access properties like x and y. To do so, simply change

var obj = lines[0] // or whatever index you want to parse

to

var obj = JSON.parse(lines[0])

https://jsfiddle.net/8h3u2vxd/1/


I would also optimise your for loop like so

const lines = this.result.split('\n');
if (lines.length > 0 && lines.length % 2 > 0) {
  throw 'Invalid data format'
}
for (let i = 0, l = lines.length; i < l; i += 2) {
  let startObj = JSON.parse(lines[i])
  let endObj = JSON.parse(lines[i + 1])
  // and so on  
}

https://jsfiddle.net/8h3u2vxd/2/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download