Home » Javascript » Updating the value of an object inside a loop using javascript

Updating the value of an object inside a loop using javascript

Posted by: admin June 30, 2018 Leave a comment


I’m currently facing a difficulty in my codes.

First i have an array of objects like this [{Id:1, Name:"AML", allowedToView:"1,2"}, {Id:2, Name:"Res", allowedToView:"1"}...] which came from my service

I assign it in variable $scope.listofResource

Then inside of one of my objects I have that allowedToView key which is a collection of Id’s of users that I separate by comma.

Then I have this code…


$scope.listofResource = msg.data
for (var i = 0; i < msg.data.length; i++) {

First I run a for loop so I can separate the Id's of every user in allowedToView key

    var allowed = msg.data[i].allowedToView.split(",");
    var x = [];

Then I create a variable x so I can push a new object to it with a keys of allowedId that basically the Id of the users and resId which is the Id of the resource

    for (var a = 0; a < allowed.length; a++) {
        x.push({ allowedId: allowed[a], resId: msg.data[i].Id });

Then I put it in Promise.all because I have to get the Name of that “allowed users” base on their Id’s using a service

    Promise.all(x.map(function (prop) {
        var d = {
            allowedId: parseInt(prop.allowedId)

        return ResourceService.getAllowedUsers(d).then(function (msg1) {
            msg1.data[0].resId = prop.resId; 

Here it returns the Id and Name of the allowed user. I have to insert the resId so it can pass to the return object and it will be displayed in .then() below

            return msg1.data[0]
    })).then(function (result) {

I got the result that I want but here is now my problem

        angular.forEach(result, function (val) {
            angular.forEach($scope.listofResource, function (vv) {
                vv.allowedToView1 = [];
                if (val.resId === vv.Id) {

I want to update $scope.listofResource.allowedToView1 which should hold an array of objects and it is basically the info of the allowed users. But whenever I push a value here vv.allowedToView1.push(val); It always updates the last object of the array.


So the result of my code is always like this
[{Id:1, Name:"AML", allowedToView:"1,2", allowedToView:[]}, {Id:2, Name:"Res", allowedToView:"1", allowedToView:[{Id:1, Name:" John Doe"}]}...]

The first result is always blank. Can anyone help me?

Here is the plunker of it… Plunkr