0

I don't know how can I convert my string data in $scope.fileContent ( I got it from my CSV file) in array. I printed my $scope.fileContent:

console.log($scope.fileContent) =

heading1,heading2,heading3,heading4,heading5
value1_1,value2_1,value3_1,value4_1,value5_1
value1_2,value2_2,value3_2,value4_2,value5_2

But I would like a function to convert it to a array like this:

[
  { heading1:"value1_1",heading2:"value2_1",heading3:"value3_1",heading4:"value4_1",heading5:"value5_1" } 
  { heading1:"value1_2",heading2:"value2_2",heading3:"value3_2",heading4:"value4_2",heading5:"value5_2" }
]

Any ideia of how to implement it in Angularjs?

I saw some examples but I didn't get with that, I guess the most releant is this.

Community
  • 1
  • 1
kfm
  • 143
  • 3
  • 17

1 Answers1

3

Using a CSV parsing library would probably be best. I've used Papa Parse before and it worked great. However, if you want to do it yourself...

function csvToArray(csvString) {
    var lines = csvString.split('\n');
    var headerValues = lines[0].split(',');
    var dataValues = lines.splice(1).map(function (dataLine) { return dataLine.split(','); });
    return dataValues.map(function (rowValues) {
        var row = {};
        headerValues.forEach(function (headerValue, index) {
            row[headerValue] = (index < rowValues.length) ? rowValues[index] : null;
        });
        return row;
    });
}

var x = "heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2";
console.log(csvToArray(x));

// OUTPUT
// [ { heading1: 'value1_1',
//    heading2: 'value2_1',
//    heading3: 'value3_1',
//    heading4: 'value4_1',
//    heading5: 'value5_1' },
//  { heading1: 'value1_2',
//    heading2: 'value2_2',
//    heading3: 'value3_2',
//    heading4: 'value4_2',
//    heading5: 'value5_2' } ]
Pace
  • 41,875
  • 13
  • 113
  • 156
  • Perfect! Thank you @Pace!! Now I need to do it but from Excel file (XLSX,XLS...) to a Array [object], if possible see this another question [link](http://stackoverflow.com/questions/41638768/angularjs-any-directive-to-convert-a-file-xlsx-xls-to-array-object-ou-other). – kfm Jan 13 '17 at 16:05