'Remove the extra " " in "lng " in array object javascript
The below code is for csv to array. I am getting an extra "space" in the output.
Example:
output : {lat: 42.546245, "lng ": 1.601554}
expected : {lat: 42.546245, "lng": 1.601554}
Help needed in removing the extra space in the "lng "header.
function initMap() {
mapLoad();
readFiles();
}
function readFiles() {
const myForm = document.getElementById("myForm");
const csvFile = document.getElementById("csvFile");
function csvToArray(str, delimiter = ",") {
// slice from start of text to the first \n index
// use split to create an array from string by delimiter
console.log(str);
const headers = str.slice(0, str.indexOf("\n")).split(delimiter);
// slice from \n index + 1 to the end of the text
// use split to create an array of each csv value row
// const rows = str.slice(str.indexOf("\n") + 1).split("\n");
const rows = str.slice(str.indexOf("\n") + 1).split("\n");
// Map the rows
// split values from each row into an array
// use headers.reduce to create an object
// object properties derived from headers:values
// the object passed as an element of the array
const arr = rows.map(function (row) {
const values = row.split(delimiter).map(Number);
const el = headers.reduce(function (object, header, index) {
object[header] = values[index];
return object;
}, {});
return el;
});
// return the array
return arr;
}
myForm.addEventListener("submit", function (e) {
e.preventDefault();
const input = csvFile.files[0];
const reader = new FileReader();
reader.onload = function (e) {
const text = e.target.result;
const data = csvToArray(text);
console.log(data);
mapLoad_1(data);
};
reader.readAsText(input);
});
}
Solution 1:[1]
When you get the title, you can remove all spaces through the trim() function
const headers = str.slice(0,str.indexOf("\n")).trim().split(delimiter);
const rows = str.slice(str.indexOf("\n") + 1).trim().split("\n");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
