Ways to update a JSON object within an array of objects

I've got an array of objects

// Extracted from the 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}]

Next, there's another array containing the users selected from a 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"}]

The goal is to update the Selected property in $scope.users if they are present in $scope.usersSelected. The approach involves looping through $scope.usersSelected and checking for corresponding UserID matches within $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;
}

Despite the code logic, the Selected properties remain unchanged. What could be causing this issue?

Lastly, clarification is needed regarding the data structure in the arrays. Why does the "$id" appear when fetching from the database, and what is the purpose of "$$hashKey" when transitioning between screens? Where do these values originate from?

Additional info: Utilizing AngularJS with ASP.NET Web API 2 for database interaction.

Answer №1

successfully tested and functioning perfectly

 $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);

Answer №2

Experimented with JavaScript.

selectedUsers =  $scope.selectedUsers;

allUsers = $scope.allUsers;

for (var j=0;j<allUsers.length;j++){

  if (selectedUsers.some(function(user) user.ID == allUsers[j].ID)) {
    allUsers[j].IsSelected = true;
    console.dir(allUsers[j]);
  }


}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to retrieve my PHP output and display it on a page using Ajax

I'm struggling to combine the functionalities of a PHP script and Ajax on my website. I want to update content without reloading the page but facing issues. Although I can send input data through Ajax, I'm unable to retrieve the results effectiv ...

Anticipate the middleware function to either invoke the next function or return a HTTP 400 status code

I am eager to delve into unit testing and am looking to test my Node API. I am utilizing Express with Typescript and Jest for testing. Prior to invoking the controller middleware, I apply the route input validation middleware to verify the validity of the ...

Using the Angular JSON pipe with angular-datatables

I am currently utilizing angular-datatables to exhibit NoSQL de-normalized data in a grid format for visualization purposes. Within my dataset, I have several intricate nested JSON objects and I intend to showcase a specific cell with formatted JSON using ...

Tips on optimizing website performance by implementing lazy loading for images and ensuring they are ready for printing

Many websites feature an abundance of images, prompting the use of lazy loading to enhance load times and reduce data consumption. But what happens when printing functionality is also required for such a website? One approach could involve detecting the p ...

Ways to create a fixed button positioned statically at the bottom of a page

Currently, I am utilizing tailwind CSS to create a webpage with Next and Back buttons for navigation. However, an issue arises when there is minimal content on the page as the button adheres to the top. For visual reference, please view the image linked be ...

"Exploring the Wonders of Regular Expressions in JavaScript: Embracing the Truth and All

Hey there! I've been working on a JavaScript script to test password field validation. As of now, I have successfully made the script display an alert when the requirements are not met. However, I am now facing an issue regarding what action to take o ...

Maya model being loaded using Three.js

I've been following a tutorial on how to load Maya models using Three.js, which you can find here. Everything is going smoothly, but the tutorial only covers loading models with a single texture. Below is the source code snippet from the tutorial: ...

What is the process for setting up a resthook trigger in Zapier?

I'm currently integrating Zapier into my Angular application, but I'm struggling with setting up a REST hook trigger in Zapier and using that URL within my app. I need to be able to call the REST hook URL every time a new customer is created and ...

What methods can be used to customize the font and background color of a website for different user groups?

Trying to incorporate a template into my project. My client has requested the following: The regular user area should feature a blue background. The professional user area should have an orange background. Is there a way to set up a condition to change ...

Changing the event when a class is active in Vue3

Question I am looking for a way to trigger an event when the 'active' class is added to an element. How can I achieve this? I believe this could potentially be accomplished using a watcher method, but I am unsure how to watch for the applicatio ...

Loading Collada files with a progress callback function can help track the

Is there a proper way to incorporate a loading bar while using the ColladaLoader? The code indicates that the loader requires three parameters, with one being a progressCallback. progressCallback( { total: length, loaded: request.responseText.length } ); ...

JavaScript on Ruby on Rails stops functioning in js.erb file

I have encountered an issue with pagination using AJAX in a view. Initially, I had two paginations working perfectly fine with their respective AJAX calls. However, when I tried to add a third pagination (following the same method as the previous two), it ...

Discovering the ways to retrieve Axios response within a SweetAlert2 confirmation dialog

I'm struggling to grasp promises completely even after reviewing https://gist.github.com/domenic/3889970. I am trying to retrieve the response from axios within a sweetalert confirmation dialog result. Here is my current code: axios .post("/post ...

React is producing a collection of <td>'s

My React code is very straightforward and it runs smoothly: function Columns(){ return ( <React.Fragment> <li>Hello</li> <li>World</li> </React.Fragment> ); } function Example(){ ...

Invoke the callback function before executing the next function

There is a function that calls an API: const response = fetch(APIfunctonName, { method: "POST", body: JSON.stringify(searchRequest), headers: { "Content-type": "application/json; charset=UTF-8", }, }) ...

Using R to retrieve values from JSON lists

My knowledge in using R is limited and I need to create a script for a school project. I have a json file with nested lists, and my task is to extract values from two specific attributes. The challenge lies in the fact that these attributes are located i ...

Showing events from MySQL database on Vue.js Fullcalendar

I am trying to fetch events from my MySQL database and pass them to my Vue component to be displayed on the FullCalendar. However, the event array is being populated with a full HTML document. Below is my EventController: public function getEvents() { ...

The error encountered is: "TypeError: req.flash does not exist as a function in NodeJs

When it comes to working with Registration on a Site, the Validation process is key. In this case, mongoose models are being used for validation and an attempt is being made to utilize Flash to showcase error messages within the Form. However, there seems ...

While executing a jssor code in SP 2007, IE experiences freezing issues

I've integrated a jssor slider with vertical navigation (without jQuery) into a Sharepoint 2007 page using CEWP. All the image links have been replaced with images stored in the SP image library, and the jssor.slider.min.js file has been uploaded to t ...

Achieving enlightenment with Satori in NextJS: Transforming SVG to PNG in a NodeJS Environment

I am currently exploring the capabilities of satori and integrating it into my next.js api routes. (I'm unable to utilize the vercel/og package). While I have successfully set everything up, I'm facing a challenge in converting the svg image gen ...