1

I have looked through some of the already present examples of this question on stack overflow but I keep getting "Undefined" and seems to be looping through every single character in the Array.

I am not all too sure how to stop this so I can have it just print out everything with property "Name"

CSV Example:

[{"Extension":"071","Company Name":"test1","Name":"Iron"},{"Extension":"072","Company Name":"test2","Name":"Blue"},{"Extension":"073","Company Name":"test3","Name":"Bloggs"},{"Extension":"074","Company Name":"test4","Name":"Best"},{"Extension":"075","Company Name":"test5","Name":"Green"}]

Client side code:

$( "#CSV-Upload" ).click(function() {
$("input[type=file]").parse({
    config: {
    header: true,
    skipEmptyLines: true,
    complete: function(results, file) {
                    console.log("This file done:", file, results);
                    var string = JSON.stringify(results['data']);
                    result.push(string);
                    console.log("CSV Array: " + string);
                    socket.emit('CSVSQL', string);
              }
    },
    complete: function() {
        console.log("All files done!");
    }
});
    $("#csv-file").val('');
});

Server side code:

function CSVSQL(csvdata) {
    if (csvdata.length > 0) {
      console.log('Current CSV data Information: \n');
      console.log(csvdata);
  for (var j = 0; j < csvdata.length; j++){
  console.log(csvdata[j].Name);
}
    } else {
      console.log('No data in that CSV file :-( \n');
    };
  }

io.sockets.on('connection', function (socket) {
    socket.on('CSVSQL', function (csvdata) {
      CSVSQL(csvdata);
    });
  });

Can anyone explain where I have gone wrong and offer some advice?

2
  • When you do console.log(csvdata);, what output you get ? Commented Feb 15, 2016 at 13:35
  • @PrashantAgrawal When I do that it prints out the whole array a couple of hundred times. Commented Feb 15, 2016 at 13:38

1 Answer 1

1

I am not all too sure how to stop this so I can have it just print out everything with property "Name"

csvdata is a string, it is not a Object yet.

Convert it to Object by doing

if (csvdata.length > 0) 
{
   csvdata = JSON.parse( csvdata ); //parse it into JSON by doing JSON.parse
   console.log('Current CSV data Information: \n');
   console.log(csvdata);
   for (var j = 0; j < csvdata.length; j++)
   {
        console.log(csvdata[j].Name);
   }
} 
Sign up to request clarification or add additional context in comments.

2 Comments

No! You parse a JSON string to a JS object. You don't parse it to JSON.
@Andy Got it! That is what I meant.

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.