John Barr John Barr - 27 days ago 8
HTML Question

JavaScript Parsing Data into an Object

interesting question for you. I'm trying to figure out the best way to parse information from my

.csv
file so that I have the raw data and can make comparisons.

What I'm trying to do right now is make an object for each person from the data that gets parsed in. So my csv file consists of:

Position,Name,Salary,Gender,Category
Chef,John Doe,40000,M,0
Clerk,Jane Doe,20000,F,1
Server,Joe Doe,30000,M,2


That's a very minor portion, I have towards 1000 different people, where obviously positions and such repeat. In my code, I currently have the javascript:

<script type="text/javascript"charset="utf-8">
var lines;
var person;

$(document).ready(function() {
//fetch text file
$.get('data.csv', function(data) {
//split on new lines
lines = data.split('\n');

//This line didn't work and gave me an error?
//person = lines.split(',');

person = data.split(',');

//window.alert(lines[1]);
//window.alert(person[5]);

});

});

</script>


Anyways, I basically have tried a few things, didn't work and deleted it. So let me go over what I have tried.


  1. Each line works correctly, so line currently gives out the entire line by line. So I tried to then split each of those lines into player based off of
    ,
    . This however gave me an error saying that
    .split
    is undefined.

  2. So next thing I tried was just splitting from the data, and that works to some degree. It splits perfectly for the first line, then gets wonky when it comes to the new line. It skips the position
    chef
    and takes
    John Doe
    . Then when it gets to the
    Category
    it correctly takes
    0
    but also prints out
    Chef
    with 2 enters below it in the same window when using
    window.alert(var[number])



Then I realize, well this isn't really going to work anyways, I want to make each person it's own object. So I want every
person
to have it's own variables:
position, name, salary, gender, category


I looked that up and I get quite a few ways of how to make it, but none take the information in through a file but manually define it right then and there. So is there some way that someone can help me with this? Do I have to do some kind of for loop, and then something interesting like:

var people = {
position:"",
name:"",
salary:0,
gender:"",
category:,
};

for(i = 5; i != eof; i+5){
people.position() = person[i];
people.name() = person[i+1];
people.salary() = person[i+2];
people.gender() = person[i+3];
people.category() = person[i+4];
}


Honestly not too sure, so any help with this would be great. Thanks!




Edit:
With the assistance of Lucas, this is where I'm currently at:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>

<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<script type="text/javascript"charset="utf-8">


var people = [];

$(document).ready(function() {
$.get('data.csv', function(data){

var lines = data.split('\n');
var properties = ["position", "name", "salary", "points", "team"]

for (var i = 0; i < lines.length; i++){
var person = lines[i].split(',');
var tmpPlayer = {}
for (var n = 0; n < person.length; n++){
tmpPlayer[properties[n]] = person[n]
}
people.push(tmpPlayer);
}

});

//correctly displays the array of every person
console.log(people);
//gives the result undefined
console.log(people[1]);
//error Uncaught TypeError: Cannot read property 'name' of undefined
console.log(people[1]["name"]);

});

</script>
</body>
</html>


The
data.csv
file:

Position,Name,Salary,Gender,Category
Chef,John Doe,40000,M,0
Clerk,Jane Doe,20000,F,1
Server,Joe Doe,30000,M,2

Answer

lines is an array not a string so you can't split it. You have to iterate through each element in lines and split this instead.

  var people = [];
  $(document).ready(function() {
    //fetch text file
    $.get('data.csv', function(data) {
      //split on new lines
      var lines = data.split('\n');

      //This line didn't work and gave me an error? 
      //person = lines.split(',');

      for (var i = 0; i < lines.length; i++){
          var person = lines[i].split(',');
          var tmpPerson = 
           {
             position = person[0];
             name = person[1];
             salary = person[2];
             gender = person[3];
             category = person[4];
           }
           people.push(tmpPerson);

        }

                //window.alert(lines[1]);
                //window.alert(person[5]);

    });

  });

If you want to dynamically assign the properties to each object you can loop over the properties instead of hardcoding them, as long as you have defined them as array somewhere.

var data = 
 `Chef,John Doe,40000,M,0
 Clerk,Jane Doe,20000,F,1
 Server,Joe Doe,30000,M,2`
  
      var people = [];
      $(document).ready(function() {

          var lines = data.split('\n');
    	  var properties = ["position", "name", "salary", "gender", "category"]
          //This line didn't work and gave me an error? 
          //person = lines.split(',');
    
          for (var i = 0; i < lines.length; i++){
                  var person = lines[i].split(',');
    		  var tmpPerson = {};
    		  for (var n = 0; n<person.length; n++){
    			tmpPerson[properties[n]] = person[n];
    		  }
               people.push(tmpPerson);
    
            }
            console.log(people)
    
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

If you are using a query to retrieve data from your file then you have to put your logging/rendering in a separate function that you call upon the completion of the $.get query. JavaScript runs these queries asynchronously so you were logging the result of people before any values were pushed to people. The below implementation should solve your issue. It seems that you are just getting started on your adventure with js so I recommend some reading on this: https://blog.risingstack.com/asynchronous-javascript/

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
    </head>
    <body>

        <script src="https://d3js.org/d3.v4.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

        <script type="text/javascript" charset="utf-8">


          var people = [];

           $(document).ready(function() {
             $.get('data.csv', function(data){

               var lines = data.split('\n');
               var properties = ["position", "name", "salary", "points", "team"]

               for (var i = 0; i < lines.length; i++){
                 var person = lines[i].split(',');
                 var tmpPlayer = {}
                 for (var n = 0; n < person.length; n++){
                   tmpPlayer[properties[n]] = person[n]
                 }
                 people.push(tmpPlayer);
               }
               render();
             });



           });


           function render(){
             alert(people[1].name);

           }
        </script>
    </body>
</html>
Comments