Sajeetharan
Sajeetharan

Reputation: 222682

How to dynamically check the fields and create array?

In my angular app, i am building a pivot table using pivot.js, which works prett well.

I need to load all the indexes from elastic search, when the user changes the index, it has to load the corresponding data to the pivot table. This i have achieved with the following code.

Now my issue is whenever user changes the index, i make a service call to get the fields of the table and the complete data of the table. I need to dynamically build an array for the pivot table.

Here is a sample, i have a product table with the fields and data corresponding.

I need to dynamically map the fields and obtain the data to be bind.

   //assume these are the fields of a table i get from the service
   $scope.ProductFields = ['Name','Code','UOM'];
   //assume this is the data i get from the rest service
   $scope.ProductData = [
    {
        Name: "ProductA",
          Code: "#f00",
          UOM:"Units"
    },
    {
          Name: "ProductB",
          Code: "#0f0",
          UOM:"Units"
    }
    // how can i build a dynamic object of product from the above data with the fields
    //something like this
    //for(dataItem in ProductData)
    //  {
    //  for(x in ProductFields)
    //  {
    //      $scope.datatobeBuild.push({fields[x]:data[dataItem]});
    //  }
    // }
    //    $scope.products=$scope.datatobeBuild;

]; 

Here is the complete Code

Upvotes: 1

Views: 63

Answers (2)

dting
dting

Reputation: 39287

You can build the objects using nest loops:

$scope.products = [];
for (var i = 0; i < $scope.ProductData.length; i++) {
  var data = $scope.ProductData[i],
      product = {};
  for (var j = 0; j < $scope.ProductFields.length; j++) {
    var field = $scope.ProductFields[j];
    product[field] = data[field];
  }
  $scope.products.push(product);
}

or

$scope.products = [];
$scope.ProductData.forEach(function(data) {
  var product = {};
  $scope.ProductFields.forEach(function(field) {
    product[field] = data[field];
  });
  $scope.product.push(product);
});

Upvotes: 1

dfsq
dfsq

Reputation: 193291

You need to construct object with dynamic keys. You can don it like this using bracket notation:

$scope.ProductData.forEach(function(data) {
    $scope.ProductFields.forEach(function(field) {
        var dataItem = {};
        dataItem[field] = data;
        $scope.datatobeBuild.push(dataItem);
    });
});

Upvotes: 0

Related Questions