0

Hello i am new in JavaScript and i would like to know how to get an array of objects with strings and an array with numbers. Is it possible to use parseInt to convert the array with the numbers in my CSV ?

this is my CSV-Data

word; arrayInt
hello; [1,20,30]
bye;   [4,50,60]

this is my output

[{"word":"hello"," arrayInt":" [1,20,30]"},{"word":"bye"," arrayInt":" [4,50,60]"}]

the code i use with the CSV-Data at the top

<head> </head>
<body>
  <form id="myForm">
    <input type="file" id="csvFile" accept=".csv" />
    <br />
    <input type="submit" value="Submit" />
  </form>
  <script>
    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
      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");

      // 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);
        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);
        var myJSON = JSON.stringify(data);
        
        console.log(myJSON); // Output of the CSV-Data

        var tmp = myJSON;
        for (var i = 0; i < tmp.length; i++) {
          let member = tmp[i];

          let arr = JSON.parse(member.arrayInt);
          tmp[i].arrayInt = arr;
        };
        console.log(tmp);
      };
      
      reader.readAsText(input);
    });
  </script>
</body>


the output i want to achieve

[{word:"hello", arrayInt: [1,20,30]},{word:"bye", arrayInt: [4,50,60]}]

1 Answer 1

1

What about this?

var tmp = [{"word":"hello","arrayInt":"[1,20,30]"},{"word":"bye","arrayInt":"[4,50,60]"}];

for(var i = 0; i < tmp.length; i++) {
  let member = tmp[i];
  
  let arr = JSON.parse(member.arrayInt);
  tmp[i].arrayInt = arr;
}

console.log(tmp);

/* outputs 
[
  { word: 'hello', arrayInt: [ 1, 20, 30 ] },
  { word: 'bye', arrayInt: [ 4, 50, 60 ] }
]
*/

EDIT

You original code has some issues. You would need to change the following in your code, in order for my suggestion to work.

In the following:

const arr = rows.map(function (row) {
    const values = row.split(delimiter);
    const el = headers.reduce(function (object, header, index) {
        //object[header] = values[index]; // <=== change this
        object[header.trim()] = values[index].trim(); // <=== into this
        return object;
    }, {});
    return el;
});

one change is needed in order to clear the spaces you have around the keys and values in your original CSV.

Next, this:

var myJSON = JSON.stringify(data);

console.log(myJSON); // Output of the CSV-Data

var tmp = myJSON;

needs to become like this

//var myJSON = JSON.stringify(data);

//console.log(myJSON); // Output of the CSV-Data

var tmp = data;

We are doing this because there's no need to stringify the data. We need to have it as an array of objects, and we'll work with that.

The rest of your the code stays as it is.

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

5 Comments

I have a another question, is it no possible to put a JSON.stringify(data) in to the tmp variable ? I am getting an Uncaught SyntaxError: "undefined" ist not valid JSON at JSON.parse (<anonymous>) at reader.onload.
undefined means that the thing you're trying to parse isn't defined. Can you add this to your actual code, before you call JSON.parse: console.log(<the thing you were trying to parse>); ?
I edited my code, i am trying to parse the value in the variable "myJSON" (from my CSV-Data on the top)
Please see the edit (below the thin horizontal line).
Omg thanks a lot! now it works completely fine :)

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.