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

JSFiddle here

Example of text file:


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


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

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  

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