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.

1
  • ng-csv could help you.. Commented Jan 13, 2017 at 3:35

1 Answer 1

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' } ]
Sign up to request clarification or add additional context in comments.

1 Comment

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.

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.