Manipulate a property within an array using JavaScript and AngularJS

I am working with an AngularJS model that looks like this:

$scope.Model = {
     Users : [{
         UserId: '',
         FirstName: '',
         LastName: ''
     }],
     Products :[{
         ProductId: '',
         Price: ''
     }]
};

Suppose I populate the 'Users' array with N users, and one of them has id=1. How can I update the 'LastName' property for that specific user (with id=1)?

If I receive a new AngularJS model as follows:

$scope.UserToUpdate ={
   UserId: 1,
   LastName: "Smith"
};

I need to iterate through the $scope.Model array in order to find and update the user with id=1, focusing only on changing the FirstName property.

Keep in mind that the target user object may be located at any position within the array, such as $scope.Model.Users[0], $scope.Model.Users[1], $scope.Model.Users[10], or even at $scope.Model.Users[N].

Answer №1

To update a user's last name, you can iterate through your list of users like this:

for (var index = 0; index < $scope.Model.Users.length; index++) {
    if($scope.Model.Users[index].UserId === $scope.UserToUpdate.UserId) {
        $scope.Model.Users[index].LastName = $scope.UserToUpdate.LastName;
        break;
    }
}

Additionally, you can use the $filter service for another approach. Here is an alternative solution:

var matchedUsers = $filter('filter')($scope.Model.Users, { UserId: $scope.UserToUpdate.UserId });
if (matchedUsers.length > 0) {
    matchedUsers[0].LastName = $scope.UserToUpdate.LastName;
}

Remember to include the $filter service as a parameter in your controller declaration when using the second solution.

Answer №2

$scope.CurrentUser = 
   $scope.UsersList.filter(function(person) { return person.FirstName == "test"; })[0];

Also, it's a good idea to include a condition to verify if the user actually exists.

Answer №3

Utilizing the $filter functionality

      var user = $filter('filter')($scope.Model.Users, 'UserId == 1');

To gain more understanding of $filter('filter'), you can visit this link

Answer №4

Give this a try! Check out the live demo here. Don't forget to monitor the console log for updates.

angular.forEach($scope.Model[0].Users, function(value1, key1) {
    var i = 0;
    angular.forEach(value1, function(value, key) {
      if (key == 'UserId' && $scope.UserToUpdate.UserId == value) {
        $scope.Model[0].Users[i].LastName = $scope.UserToUpdate.LastName;
      }
      i++;
    });

  });

The code above is responsible for updating the LastName property within the Model object based on the UserToUpdate object with an ID of 1.

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

What is the best way to retrieve the scope of ng-repeat from another directive located on the same element as ng-repeat?

Is it possible to access a property from the ng-repeat scope in another directive within the same element as the ng-repeat directive? For instance, I would like to be able to use the child.class property in this scenario: <div ng-class="{{ child.class ...

The fadeIn callback doesn't seem to function properly when triggered within the success function of jquery.ajax

Using AJAX, I fetch some data and prepend it to the body. Once displayed, I need to execute some client-side operations on this new element, such as rendering Latex using codecogs' script. Below is a snippet of my code: $.ajax({ /* ... */ success: fu ...

No Angularjs redirection without the "onload" event

In my search for a solution, I came across this answer but it did not quite fit my needs: Pass onload event through redirect The issue I'm facing is that I want the AngularJS section of my application to reload something when the user is redirected ...

Divide an HTML file into separate documents upon submitting a form

Is there a way to input HTML into a text area, then upon submission, have the system read the file, identify the class selector, and separate the HTML into multiple files saved in a directory? If you have any thoughts on how this could be accomplished, pl ...

Currently, my goal is to create PDFs using Angular

<button class="print" (click)="generatePDF()">Generate PDF</button> Code to Generate PDF generatePDF(): void { const element = document.getElementById('mainPrint') as HTMLElement; const imgWidth = 210; ...

Tips for exchanging JSON data between HTML and PHP using jQuery Ajax?

Hello there! I am just starting to learn PHP and jQuery, and I have been experimenting with some code to understand how things work. However, I seem to be having issues with sending data back and forth between my webpage and the PHP file on the server. Her ...

Adding Packages to AngularJS: A Step-by-Step Guide

Recently, I decided to dive into learning AngularJS and NPM on my own. Using the book Professional AngularJS by Diego Netto and Valeri Karpov as my guide, I successfully installed the application with Yeoman and ran it using Grunt. However, I've hit ...

Exploring and Troubleshooting HTML and JavaScript with Visual Studio Code Debugger

Visual Studio Code Version 1.10.2 Windows 10 I am currently experimenting with VS Code and would like to debug some basic HTML and JavaScript code. The instructional video found at http://code.visualstudio.com/docs/introvideos/debugging mentions that ...

Collecting the timestamp when the page is loaded and then comparing it with the timestamp when the form is

I have implemented an anti-spam time trap in my application (although I realize its effectiveness may not be 100%, it serves as a temporary solution) that functions as follows: 1) Upon loading a page, a hidden input is populated with a timestamp using Jav ...

Implement a jQuery feature to gradually increase opacity as the user scrolls and the page loads

On a dynamically loaded page via pjax (except in IE), there are several links at the bottom. Whenever one of these hyperlinks is clicked, the page scrolls to the top while still loading. Although I am okay with this behavior, I'm curious if it' ...

Sending form data using javascript without refreshing the page

I have a wall/social system similar to Facebook where users can post statuses. I want to add the functionality for users to like, dislike, and comment on a status without the page reloading. How can I achieve this with the form below? if(empty($_GET[&apos ...

When querying the model, the result may be undefined

I'm encountering an issue where I can't access the content of an array of documents in my model and it's returning undefined. Here is the model structure (Project.js): var mongoose = require('moongoose'); var Schema = mongo ...

What exactly is the functionality of the `require('atom')` method?

Atom provides various global APIs that can be easily accessed through require('atom') How does this mechanism function? Despite not being a declared dependency, Atom packages are able to utilize these global APIs. Additionally, is it possible to ...

Checking the existence of a user's email in Node.js

Hey there! I am new here and currently learning Node.js with Express. I'm trying to find a way to check if a user's email already exists in the database. Here is what I have so far: const emailExists = user.findOne({ email: req.body.email }); if ...

The raycaster fails to detect collision with the .gltf model

When using the raycaster to detect mouse intersection with a cube, everything works perfectly: raycaster.setFromCamera(mouse, camera) const intersects = raycaster.intersectObject(cubeMesh) if(intersects.length > 0) console.log('intersecting ...

Synchronize information between two drop-down lists

I am currently utilizing the boostrap library to create a pair of dropdown lists. My goal is to have the items in the second dropdown list dynamically update based on the selection made in the first dropdown. Within my code, there exists a dictionary name ...

Utilizing JSON and Javascript to dynamically generate and populate interactive tables

Here's how I've structured my JSON data to define a table: var arrTable = [{"table": "tblConfig", "def": [{"column": "Property", "type": "TEXT NOT NULL"}, {"column": "Value", "type": "TEXT NOT NULL"}], "data": [{"Property ...

Comparison: executing an immediately invoked function expression (IIFE) and a separate

During my recent refactoring of some legacy code, I stumbled upon the following example: // within another function const isTriggerValid = await (async () => { try { const triggers = await db.any(getTriggerBeforeBook, { param ...

Issue with displaying entire object using Jest and console.dir

I'm having trouble displaying an error in my Jest test because it's not showing all the levels as expected. import util from 'util' describe('Module', () => { it('should display all levels WITHOUT util', () =& ...

.load() not triggering for images that are not in the cache - jquery

In Safari and Opera, the callback function of .load doesn't wait for uncached images to be fully loaded. With cached images, it works perfectly fine. The code may seem a little complicated, but I'll do my best to simplify it... So, here is my J ...