Studento919
Studento919

Reputation: 635

Loop through JS Object Array for specific properties

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?

Upvotes: 1

Views: 482

Answers (1)

gurvinder372
gurvinder372

Reputation: 68393

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);
   }
} 

Upvotes: 1

Related Questions