1

I'm tiying to build an excel uploader app. Right now, I can get the data from the excel file and send it to an API to store the info.

But i need something else, and is to asign to each value the id of the excel, which i'll get after save it first.

This is how i get the excel data before store it:

$scope.loadWorksheet = function(e){

        var file = e.target.result;
        var workbook = XLSX.read(file, { type: "binary" });


        var sheetName = workbook.SheetNames[0];
        $scope.sheet = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]);

       console.log($scope.sheet);

        $scope.$apply();

      };

Let's say i get the next array:

[{Name: "Chuck", Age: "30"},
{Name: "Marcus", Age: "18"},
{Name: "Shelly", Age: "29"}]

How can i add to each record the id of the document?

Per example, after save the document i get on the response the id:

$scope.IdDocument = 15;

And what i need is to put it on every record, like this:

[{Name: "Chuck", Age: "30", DocumentId: "15"},
{Name: "Marcus", Age: "18" DocumentId: "15"},
{Name: "Shelly", Age: "29" DocumentId: "15"}]

There's a way to do that? Hope you can help me.

I'm using AngularJs and Javascript.

4 Answers4

1

You need forEach, with angularjs you can use angular.forEach

DEMO

var array = [{Name: "Chuck", Age: "30"},
{Name: "Marcus", Age: "18"},
{Name: "Shelly", Age: "29"}];

array.forEach(function(obj) { obj.DocumentId = "15"; });

console.log(array);
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

You can just iterate over your array and add the field as follows

var people = [{Name: "Chuck", Age: "30"},
                  {Name: "Marcus", Age: "18"},
                  {Name: "Shelly", Age: "29"}
                 ];
    
    people.forEach(p => p.DocumentId = "15");
    console.log(people)
Punith Jain
  • 1,647
  • 1
  • 15
  • 21
Rishikesh Dhokare
  • 3,559
  • 23
  • 34
1

Use map function.It will return the updated array

var oldArray = [{
    Name: "Chuck",
    Age: "30"
  },
  {
    Name: "Marcus",
    Age: "18"
  },
  {
    Name: "Shelly",
    Age: "29"
  }
];

var newArray = oldArray.map(function(item) {
  item.DocumentId = '15';
  return item;

})

console.log(newArray)
brk
  • 48,835
  • 10
  • 56
  • 78
0

iterate over your array object using for loop

var people = [{Name: "Chuck", Age: "30"},
             {Name: "Marcus", Age: "18"},
             {Name: "Shelly", Age: "29"}];


 for(var i=0 ; i<people.length;i++){
      people[i].age = "10";
 }
Hussain
  • 87
  • 5