[英]Convert csv file into a javascript object
I have a csv file which contains a list of airports and its coordinates.我有一个 csv 文件,其中包含机场列表及其坐标。
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?我如何将内容解析为 Javascript object 像这样?
{
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.您在新行上拆分,在逗号上拆分,并使用 reduce 来制作对象。
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.我相信有人可以通过这个获得一些 CodeGolf 的乐趣,但这里有一个简单的解决方案。 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.
这与数据集非常相关,因此我建议在提交此解决方案之前考虑您是否会有不同形状的 csv(如不同的标题、行+列等)。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.