2

I want to be able to store the the data in my CSV files so I can read it easier and serve it to a webpage.

The CSV is in the following format, probname1:"meat1", probename2:"meat2".......

If I paste the data in manual like https://www.w3schools.com/js/tryit.asp?filename=tryjs_array_object it works, I also tried setting up my array dirrentely and using MGot90's method from Read CSV headers using Javascript

But I can only ever call 1 full value of each object e.g settings[0], and not call the object by its name e.g settings["ProbeName1"] I want the following to beable to output meat1 with the following in the CSV file. updatevalues.csv = probname1:"meat1", probename2:"meat2"

loadData();
function loadData() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
parseCSV(this.responseText);
}
};
xmlhttp.open("GET", "js/updatevalues.csv", true);
xmlhttp.send();
}

function parseCSV(string) {
var allTextLines = string;
var settings = [];
var settings = allTextLines.split(",");
document.getElementById("demo1").innerHTML = settings["ProbeName1"];
}`

currently I can only get id=demo1 to output ProbeName1:"meat1" using settings[0]. If I use settings["ProbeName1"] it will display undefined.

2 Answers 2

1

This function will convert your csv into a JSON object:

function parseCSV(str) {
    var allTextLines = str;
    var settings = [];
    var settings = allTextLines.split(",");
    var results = {};
    var name, val, idx;
    for (var i = 0; i < settings.length; i++) {
        idx = settings[i].indexOf(':');
        name = settings[i].substring(0, idx);
        val = settings[i].substring(idx+2, settings[i].length-1);
        results[name] = val;
    }
    return results;
}

Working in fiddle: https://jsfiddle.net/p3t7Lv28/

That code strips the quotes off the values by using idx+2, length-1

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

1 Comment

Thanks worked, I spent a few weeks trying to get this to work :)
0

Why you need that i dont know but may be you can use SheetJS tool.Its for showing the excel on the web.

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.