erasmo carlos
erasmo carlos

Reputation: 682

AngularJS how to format an array

I am working on an app that read an excel file and upload its contents to a ui.grid. That part is working good. I need to also create a second array with the same data but a different purpose, to use on a 3rd party api call.

The array needs to have this format:

{
  "users": [
    {
      "name": "frank",
      "email": "[email protected]"
    },
    {
      "name": "mike",
      "email": "[email protected]"
    }
  ]
}

currently my array looks like:

data: Array(5)
    0:
        Email: "[email protected]"
        Name: "Jack Anderson"
    1:
        Email: "[email protected]"
        Name: "Ed Johnson"
    2:
        Email: "[email protected]"
        Name: "Dead Poole"
    3:
        Email: "[email protected]"
        Name: "Hank  Schmidt"
    4:
        Email: "[email protected]"
        Name: "Steven Alves"

The code I am using:

$scope.arr = new Array;

// SEND THE FILES.
$http(request)
    .then(function (data) {

        angular.forEach(data.data, function (item) {
            var b = {
                Name: item.Name,
                Email: item.Email
            };

            $scope.arr.push(b);
        });

    }).error(function (error) { });
}
$scope.gridData = { data: 'arr' }; 

How can I change the code, or add code, to create an array that meets the format I need?

Thank you for your help. Erasmo

UPDATE

This is my code after adding the recommendation

.controller('myController', function ($http) {

    var formdata = new FormData();
    var vm = this;

    vm.getTheFiles = function ($files) {
        angular.forEach($files, function (value, key) {
            formdata.append(key, value);
        });
    };

    // SEND FILES TO THE API USING POST METHOD.
    vm.uploadFiles = function () {

        var request = {
            method: 'POST',
            url: '/api/fileupload/',
            data: formdata,
            headers: {
                'Content-Type': undefined
            }, transformRequest: angular.identity
        };

        vm.arr = new Array;

        // SEND THE FILES.
        $http(request).then(function (data) {

                angular.forEach(data.data, function (item) {
                    var b = {
                        name: item.Name,
                        email: item.Email
                    };

                    vm.arr.push(b);
                });
        }).catch(function (error) {
            console.log("Error: " + error);
        });

        var items = vm.arr.map((item) => {
            return {
                name: item.name,
                email: item.email
            };
        });

        var panelists = {
            "panelists": items
        }
        console.log(panelists);

    }

    vm.gridData = { data: 'arr' };

Upvotes: 0

Views: 75

Answers (2)

bharat.goli
bharat.goli

Reputation: 159

I guess you are using old version of angular. So I use vanilla JavaScript

You can create a function $scope.getGridData just to transform your data to your desired output

$scope.arr = [];

// function that transforms your response data to gridData

$scope.getGridData = function(data) {
  if (!data) {
    return [];
  }
  var returnData = [];

  for (var i = 0; i < data.data.length; i++) {
    returnData.push({ name: data[i].Name, email: data[i].Email });
  }

  return { users: returnData };
};


// Your http request
$http(request).then(function(data) {
  // your current array
  $scope.arr = data.data;

  // your transformed grid data is assigned to gridData
  $scope.gridData = $scope.getGridData(data.data);
}).error(function (error) { });

You need to assign values to $scope.arr and $scope.gridData inside then block because the data is not available until http request is resolved.

So now you have $scope.arr which as your current array.

And you have $scope.gridData which has your transformed data

Upvotes: 2

Bucket
Bucket

Reputation: 7521

After your loop, you can use Array.map() to rename the keys of your array objects to all lowercase, then you can place that array in a new object as the "users" property:

var foo = $scope.arr.map((item) => {
    return {
        name: item.name;
        email: item.email;
    };
});

var bar = {
    "users": foo
}

Of course, rename these variables to more accurately reflect their purpose.

If you need to only provide the first name, you need to split the string at the space:

item.name.split(' ')[0];

Another approach to consider is renaming the properties Email and Name to email and name in your original loop so that the format is the same and you can reuse the same array. If this object is being passed to a grid that is set up to look for the capitalized names, you may need to reconfigure it to accommodate this change. This would look something like:

angular.forEach(data.data, function (item) {
    var b = {
        name: item.Name,
        email: item.Email
    };

    $scope.arr.push(b);
});

And in whatever call you need to make to the third-party endpoint, you can add this array on the fly in a similar way:

someThing.doThing({
    "users": $scope.arr;
});

Upvotes: 1

Related Questions