0

I have a csv file which contains a list of airports and its coordinates.

JFK, 40.63980103, -73.77890015
LAX, 33.94250107, -118.4079971
SEA, 47.44900131, -122.3089981

How would I parse the content into a Javascript object like this?

{ 
  JFK: { lat: 40.63980103, lng: -73.77890015 },
  LAX: { lat: 33.94250107, lng: -118.4079971 },
  SEA: { lat: 47.44900131, lng: -122.3089981 }
}
2
  • stackoverflow.com/… Commented Jul 16, 2020 at 14:48
  • 2
    split it on new lines, loop over split on commas, change it to an object. Commented Jul 16, 2020 at 14:49

2 Answers 2

2

You split on new lines, split on commas, and use reduce to make the objects.

var csv = `JFK, 40.63980103, -73.77890015
LAX, 33.94250107, -118.4079971
SEA, 47.44900131, -122.3089981`;

// split on lines
const data = csv.split(/\n/).reduce((obj, line) => {
  // split on commas
  var parts = line.split(/,/);
  obj[parts[0].trim()] = {
    lat: +parts[1],
    lng: +parts[2],
  };
  return obj;
}, {});

console.log(data)

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

2 Comments

Watch out in case the CSV has commas, newlines and quotes in a field, such as: "Newton, ""Jimmy"" James", which results in field: Newton, "Jimmy" James. In that case you need a proper CSV parser such as github.com/peterthoeny/parse-csv-js
@PeterThoeny When it is simple, you do not need a parser.
1

I'm sure someone could have some CodeGolf fun with this one but here's a simple solution. This is very coupled to the data set so I'd suggest considering whether you'll have different shaped csv's (as in different headers, row+columns, etc) before committing to this solution.

const data = `JFK, 40.63980103, -73.77890015
LAX, 33.94250107, -118.4079971
SEA, 47.44900131, -122.3089981`

const splitByLines = data.split(/\n/)
const splitByCommas = splitByLines.map(arr => arr.split(','))

const output = {}
splitByCommas.map(([loc, lat, lon ]) => {
  output[loc] = { lat, lon }
})

console.log(output)


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.