1

I'm going to preface this with the fact that the JSON I am getting is coming from angular-csv-import and I am trying to clean up the strings within the keys, values.

I have read this thread but I don't want to to use JQuery so I edited to be in a more angular way.

Remove leading and trailing spaces in object keys and values

Here is the data I am getting from the CSV file

[
 {
"TRAIN_LINE":"El",
" ROUTE_NAME":"Brown Line",
" RUN_NUMBER":"E102",
" OPERATOR_ID":"SJones"
 },
 {
"TRAIN_LINE":"Metra",
" ROUTE_NAME":"UPN",
" RUN_NUMBER":"M405",
" OPERATOR_ID":"AJohnson"
 }
]

To send the data to my api I need it to have no leading or trailing spaces to minimize clean up and keep it consistent no matter what the csv file uploaded is.

I'm able to remove the space using .trim() on the keys and values but it is not updating in the dataset I am going to send to the server. Any help much appreciated. Here is my code in my controller.

$scope.postData = function (result) {
    angular.forEach(result, function (index) {     
        angular.forEach(index, function (k, v) {
            k = k.trim();
            v = v.trim();
            return k;
            return v;       
        });
        return index;
        console.log(index);
    });
    console.log(result);     
};

Note if I log k and v the spaces are removed, but how do I push that to the results.

Community
  • 1
  • 1
Philip Chmalts
  • 2,268
  • 2
  • 12
  • 11

2 Answers2

0
$scope.postData = function (results) {

    var newResults = [];

    angular.forEach(results, function (index) {

        var newObj = {}; // cue the trumpets

        angular.forEach(index, function (v, k) {
            k = k.trim();
            v = v.trim();
            newObj[k] = v;      
        });

        newResults.push(newObj);

        return index;
        console.log(index);
    });

    console.log(newResults);     
};
Danny Bullis
  • 3,043
  • 2
  • 29
  • 35
  • YESSS!!!! That pretty much did it. Except now the keys and values are backwards, easy fix though. Just needed to do this angular.forEach(index, function (k, v) { k = k.trim(); v = v.trim(); newObj[v] = k; }); – Philip Chmalts May 24 '15 at 23:10
  • word. I'll update my answer so it reflects that. Cheers dude. Don't forget to click the answer check mark :]. – Danny Bullis May 24 '15 at 23:14
0

The other answer will work but I think this is more of the style you were going for. Also note that the parameters are v, k.

angular.forEach(results, function (index) {     
  angular.forEach(index, function (v, k) {
    delete index[k];
    index[k.trim()] = v.trim();
  });
});
Andy Gaskell
  • 31,495
  • 6
  • 74
  • 83