简体   繁体   中英

Convert csv file into a javascript object

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 }
}

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)

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)


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM