0

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}

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.