Willy Willy - 5 months ago 16
Javascript Question

How to modify json object in array of object

I have an array of object

// This is should be taken from database
$scope.users = [{"$id":"1","UserID":3,"Name":"A","Selected":false},{"$id":"2","UserID":4,"Name":"B","Selected":false},{"$id":"3","UserID":5,"Name":"C","Selected":false},{"$id":"4","UserID":6,"Name":"D","Selected":false}]


Then there is an array that contains the selected users from previous screen

$scope.usersSelected = [{"$id":"3","UserID":5,"Name":"C","Selected":true,"$$hashKey":"object:83"},{"$id":"4","UserID":6,"Name":"D","Selected":true,"$$hashKey":"object:84"}]


I want to update the
Selected
properties of
$scope.users
if they are found in
$scope.usersSelected
. So I iterate the
$scope.usersSelected
then search its
UserID
in the
UserID
of
$scope.users


for (var i = 0; i < $scope.usersSelected.length; i++) {
var obj = $.grep($scope.users, function (e) { return e.UserID == $scope.usersSelected[i].UserID; });
obj.Selected = true;
}


but the
Selected
properties won't be updated. What's wrong with the code above?

Second, I need an explanation regarding the data in array above, why there is always
"$id"
when I populate the data from the database and also
"$$hashKey"
when I get the data from another screen? Where do these values come from?

Notes: I'm using AngularJS with ASP.NET Web API 2 to get the data from database.

Answer

tested working absolutely fine

 $scope.users = [ {
        "$id" : "1",
        "UserID" : 3,
        "Name" : "A",
        "Selected" : false
    }, {
        "$id" : "2",
        "UserID" : 4,
        "Name" : "B",
        "Selected" : false
    }, {
        "$id" : "3",
        "UserID" : 5,
        "Name" : "C",
        "Selected" : false
    }, {
        "$id" : "4",
        "UserID" : 6,
        "Name" : "D",
        "Selected" : false
    } ];

    $scope.usersSelected = [ {
        "$id" : "3",
        "UserID" : 5,
        "Name" : "C",
        "Selected" : true,
        "$$hashKey" : "object:83"
    }, {
        "$id" : "4",
        "UserID" : 6,
        "Name" : "D",
        "Selected" : true,
        "$$hashKey" : "object:84"
    } ]
    var users = $scope.users;
    var usersSelected = $scope.usersSelected;
    for (var i = 0; i < users.length; i++) {
        for (var j = 0; j < usersSelected.length; j++) {
            debugger
            if (users[i].UserID == usersSelected[j].UserID) {
                console.log(users[i].UserID)
                console.log(usersSelected[j].UserID)
                users[i].Selected = true;

            }
        }

    }

    console.log(users)
    console.log(usersSelected);