Swapping items within Angular's forEach()

I am working with an array of objects and using a forEach() function in my code. Here is the structure:

$scope.things = [
    {x: 2},
    {x: 4},
    {x: 5}
];

angular.forEach($scope.things, function(thing) {

    //You can uncomment one line at a time

    //thing.x += 10;         // <--- works
    //thing.k = thing.x + 1; // <--- works
    //thing = {k: thing.x + 10, o: thing.x - 1};  // <--- doesn't work

});

console.log($scope.things);

When I say "works", it means:

  • x gets incremented by 10, resulting in {x: 12}, {x: 14}, {x: 15}
  • k property is added to each object, resulting in
    {x: 2, k: 3}, {x: 4, k: 5}, {x: 5, k: 6}
  • The original object remains unchanged even if modifications are made.

My queries are:

  • What is the reason behind this behavior?
  • Is this the expected outcome?
  • How can I replace each object entirely in the array?

Answer №1

What could be the reason for this occurrence?

This situation arises because the variable thing is simply a placeholder. You have the flexibility to reassign the value of a variable, including a parameter variable, without impacting the values stored in an object.

Is this behavior what you anticipated?

Absolutely.

How can I fully substitute each instance of thing?

To alter the value of an object's property, you must specifically target it during assignment. The forEach iterator function receives value, key, and obj as parameters. By referencing the object along with its property name, you can execute

obj[key] = { whatever: "you desire" }
to modify the property's value.

angular.forEach($scope.things, function(thing, key, things) {

    //Execute only one line at a time

    //thing.x += 10;         // <--- works
    //thing.k = thing.x + 1; // <--- works
    //thing = {k: thing.x + 10, o: thing.x - 1};  // <--- doesn't work

    //things[key] = {k: thing.x + 10, o: thing.x - 1}; // <--- works!
});

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

Shared variables in Node.js allow for multiple users to access different entry points simultaneously

In the process of transitioning my node-js application from a single-tenant database to a multi-tenant database, I am facing some challenges. The application code is accessed through an express api and various services are run through different entrypoints ...

What could be causing the issue with running npx create-react-app my-first-app?

Encountered issues when attempting to execute npx create-react-app. Need assistance troubleshooting the error messages preventing the command from running. View Screenshot of Terminal with stacktrace Error: EPERM: operation not permitted, mkdir 'C:& ...

Guide to reversing the sequence of characters forming a sentence

Trying to solve the challenge of reordering a character array that spells out a sentence backwards or out of order, with words separated by spaces. The goal is to rearrange it into the correct/reversed format so that instead of spelling World Good Hello, i ...

Is array.length access cached by NodeJS?

Lately, I've been pondering whether accessing the array.length getter is cached by NodeJS. I've searched for conclusive answers about JS interpretation in browsers, but since I am working on apps in Typescript, that information does not directly ...

The appearance of the logout button may differ depending on the web browser being used

I have implemented a straightforward logout button using the following code: <li><a href="http://localhost:8666/web1/profile/mainpage/logout.php" onclick="return confirm('Are you sure to logout?');">Log Out</a>&l ...

Include an additional capital letter at the beginning of each new item in ng-repeat

My array is organized as follows: [aa,ab,ba,bb] My desired rendering is: A aa ab B ba bb What changes can I make to this loop to achieve this? <div ng-repeat="item in array" > {{item}} <br> </div> ...

Attempting to modify the background color of an iFrame in Internet Explorer

I am experiencing an issue with my webpage where the iFrame is displaying with a white background in IE, while it shows up with a blue background in Firefox and Chrome. I have attempted various solutions to make the background of the iframe blue or transpa ...

Problem with Angular's ng-repeat functionality

Here is an example of a controller: app.controller('HomeController', function($scope) { $scope.buttonList = [ { href: "http://example.html", cssClass: "", iconBeforeCssClass: "", labelCssClass: "", la ...

The jQuery UI Tab is failing to scroll within its container

Scenario : I am facing an issue with a scrollable container in IE8. The containing div is supposed to be scrollable and it holds my jquery UI tab div. Issue: While scrolling the container in IE8, other content within it also scrolls, but the jQuery UI t ...

Steps for enabling (almost) unidirectional communication from a client to a server

Is there a request method in Javascript that allows me to send message m and data v to the server without having to deal with the response? If not, what is the best way to return a minimally acceptable string back to the client, which will not be processed ...

Guide to forming an array by extracting specific properties from a nested JSON array using javascript

Currently, I have this list: list = { id: 1, arr: [ {index : 1 , description: "lol" , author: "Arthur"}, {index : 2 , description: "sdadsa" , author: "Bob"}, {index : 3 , desc ...

ReactJS - Element not specified

I'm experiencing a specific issue with the component below related to the changeColor() function, which is triggering an error message: TypeError: Cannot set property 'color' of undefined This error seems to be isolated within this compo ...

What location is ideal for making API calls with React and Redux-thunk?

After extensively searching on StackOverflow.com and across the internet, I couldn't find a similar question. Therefore, please refrain from giving negative reputations if you happen to come across one as I truly need reputation at this point in my li ...

Arduino's innovative 3-dimensional array technology

I am currently engrossed in creating my 4x4x4 LED cube, and I have set out to develop my own code for it. However, I have hit a roadblock when dealing with 3D arrays. I initially declared multiple arrays within void setup(), even attempting to place them i ...

Arrange the array based on the order of the enumeration rather than its values

Looking to create an Array of objects with enum properties. export enum MyEnum { FIXTERM1W = 'FIXTERM_1W', FIXTERM2W = 'FIXTERM_2W', FIXTERM1M = 'FIXTERM_1M', FIXTERM2M = 'FIXTERM_2M', FIXTERM3M = 'FIX ...

Is there a way to locate a parent class starting from a child class, and subsequently track down another child class from the parent?

I am facing a challenge with multiple tags structured like this: <div class="A"> <div class="B1">...</div> <div class="C1">Hello World!</div> <div class="C2">World Hell ...

Combining ServiceStack with MVC and AngularJs for optimal integration

Setting up web.API with MVC is a breeze - just keep the WebApiConfig.cs as default, create a new web.API controller, and then in your javascript make calls using $http.get("api/..."). I'm interested in achieving the same functionality using service s ...

encountering difficulty with loading JavaScript code while customizing form fields in Symfony/Sonata Admin

I have been attempting to personalize a field in a form created with the Sonata Admin Bundle. I followed the solution provided in this article: Customize form field rendering. Apart from customizing the form field, I also aimed to implement an autocomple ...

Is there a way to prevent jshint errors related to global variables in my web file?

My protractor test script file is structured as follows: var TestPage = function () { this.detailsTab = element(by.id('detailsTab')); .. However, I am encountering numerous errors stating that element and by are not defined. Is there a ...

Sending data to a server using the select element within a form

I am dealing with a controller that looks like this: $scope.disciplines = disciplines; $scope.discipline = disciplines[0]; This controller contains an array. Within my form, I have the following elements: <form class="form-horizontal" ng-submi ...