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 }
}
-
stackoverflow.com/…Andrea Giammarchi– Andrea Giammarchi2020年07月16日 14:48:47 +00:00Commented Jul 16, 2020 at 14:48
-
2split it on new lines, loop over split on commas, change it to an object.epascarello– epascarello2020年07月16日 14:49:39 +00:00Commented Jul 16, 2020 at 14:49
2 Answers 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)
answered Jul 16, 2020 at 15:00
epascarello
208k20 gold badges206 silver badges246 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Peter Thoeny
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 epascarello
@PeterThoeny When it is simple, you do not need a parser.
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
lang-js