Adding multiple new properties to an object in AngularJS through iteration

I am looking to merge two arrays together. Here, I have a piece of code where I want to extract each user row from the foo array and create a new array.

UserService.GetUserFoo(id)
        .success(function (data) {         
         data = angular.fromJson(data); //[{id:1, u_id:1, foo:"a"}{id:2, u_id:2, foo:"b"}]

         angular.forEach(data, function(user){
                getUser(user.u_id)   }); //FUNCTION CALL       
         }).
        error(function(error) {
         //do something       
      });

In this part of the code, the getUser function is invoked in the GetUserFoo service to populate a new array named $scope.users

$scope.users = []; //[{id:1, name:"Ed"},{id:2, name:"Jim"}]
      var getUser = function(id) {
            UserService.GetUserById(id)
            .success(function (data) {
              data = angular.fromJson(data);
                $scope.users.push(data); //                
            }).error(function(error) {
                       //do something
            });
        };

QUERY --> How can I insert each foo field into the corresponding $scope.users object so that in my view I can display something like this

//[{id:1, name:"Ed", foo:"a"}{id:2, name:"Jim", foo:"b"}]

<li ng-repeat="user in users">
<h2>{{user.name}}</h2>
<p>{{user.foo}}</p>
</li>

Answer №1

function combineArrays($scope){
    $scope.users=[
        {id:1,name:"user 1"},
        {id:2,name:"user 2"}
    ];
    $scope.fooUser=[
        {id:1,foo:"foo 1"},
        {id:2,foo:"foo 2"}
    ];
    
    $scope.insertProperty=function(){
       
        for(var i=0;i<$scope.users.length;i++){
            for(var j=0;j<$scope.fooUser.length;j++){
                if($scope.users[i].id==$scope.fooUser[j].id)
                    $scope.users[i].foo=$scope.fooUser[j].foo
            }
        }
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="combineArrays">
    <ul>
        <li ng-repeat="user in users">
             <h2>{{user.name}}</h2>

            <p ng-cloak>{{user.foo}}</p>
        </li>
    </ul>
    <button ng-click="insertProperty()">insert property</button>
</div>

this example demonstrates how to merge properties from two arrays without worrying about their length or order

Answer №2

When both arrays are of the same length and each unique id aligns in the corresponding position within both arrays:

let originalArray = angular.copy($scope.users);
let newDataArray = angular.copy(data);

$scope.users = combineArrays(originalArray, newDataArray);

function combineArrays (arrayOne, arrayTwo) {
  for (let index in arrayOne) {
    angular.extend(arrayOne[index], arrayTwo[index]);
  }
  return arrayOne;
}

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

Confirming the Checkbox Field - ASP.NET with the Power of jQuery

I am currently working on a straightforward validation process for checking agreements using an asp:checkbox and an asp:button click. When the button is clicked, I have this function being called: OnClientClick="ValidateConditions();" The function itsel ...

How can I display the value of a clicked text in the search input box using AngularJS and Bootstrap?

I have a search box that functions like Google, with a list of text values displayed below. I would like to be able to click on any of these text values and have it automatically appear in the search box. Is there a way to achieve this? ...

Angling for Success: How to Test Immediately Invoked Functions within a Directive Controller Using Jasmine

Imagine I have a directive: .directive('myDir', function(TemplateHandler){ return { ... controller: function(ExploreCmd){ this.foo = { bar: function(){...} }; this.foo.bar(); } } }); I want to verify t ...

Issue with ngRepeat directive

I'm attempting to display an array in a table Below is the relevant code snippet js: var d = [[ '12:00', 'X-Files', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis non nisi in velit tristique scelerisque. ...

Converting an image to a byte array in JavaScript

Does anyone know how to manipulate binary files in Javascript similar to C? I'm currently facing a critical scenario where I need to create a flipped image. Unfortunately, I don't have access to CSS, canvas, HTML, or the DOM - so I need to accomp ...

Using node-native to authenticate in MongoDB is a surefire way to ensure the

I'm currently facing an issue while attempting to save a document in MongoDB within my Nodejitsu/MongoHQ application. Everything works perfectly locally, but the MongoHQ database requires authentication and it fails even with the correct user/password ...

Utilizing object categories to split arrays and extract values in JavaScript with Highcharts

After receiving an array with a number of objects, my goal is to split it based on categories. Once the sum value of categories in the array reaches 15, I need to further divide the array as shown below for better organization. Any assistance would be gre ...

What is the process for getting non-event javascript instructions to function properly once a DOM element has been added

After inserting DOM elements (such as an AJAX response), event-delegation is necessary to ensure that events work properly. But what about basic JavaScript instructions? All instructions are organized by affected PHP page to simplify code updates and avoi ...

concealing additional content within a DIV using ellipsis

Looking to conceal additional text within my DIV element with ellipsis (...) at the end Currently using: <div style="width:200px; height:2em; line-height:2em; overflow:hidden;" id="box"> this is text this is text this is text this is text </div ...

Get started with adding a Typescript callback function to the Facebook Login Button

I am in the process of implementing Facebook login into my Angular7 application using Typescript. Although I have successfully integrated Facebook's Login Button plugin for logging in, I am facing issues with providing a callback method to the button& ...

observing the value of the parent controller from the UI router state's resolve function

I am facing an issue in my AngularJS application while using ui-router. There are three states set up - the parent state controller resolves a promise upon a successful request, and then executes the necessary code. In the child state portfolio.modal.pate ...

next-images encountered an error during parsing: Unexpected character ''

Having trouble loading images dynamically with next-images: //Working <Image src={require(`../../images/exampleImage.jpg` )}/> However, I want to use a dynamic URL like this: //Not working <img src={require(`../../images/${image}.jpg` )}/> Th ...

Tips for displaying Ajax response in a modal popup

I have a link that, when clicked, sends an AJAX request and successfully receives a response in the form of an HTML file, which I then append to a div. However, I want to display this div as a modal popup and I have attempted the following: In the HTML fi ...

Issue with jQuery click event not activating on initial click but functioning properly on the subsequent click

I am currently implementing the jquery.ime editor in my project, which allows for multi-language editing capabilities. The library I am using can be found here. By default, the language JSON files are loaded on "change" events. However, I would like this f ...

Why isn't httpUploadProgress functioning correctly with Buffer data?

Recently, I have ventured into the world of node.js/express as I am attempting to create a multiple image uploading application utilizing cloudfront and an s3 bucket. My goal is to display a progress bar for the user by integrating socket.io for real-time ...

Hide <a> by setting its display property to none

Below is the HTML code: <td> <a class="link" href="#"> <span class="download">Link</span> </a> <a class="link" href="#"> <span class="csvdownload">Link 2</span> </a> </td> I am lo ...

The ins and outs of function returns and callback mechanisms

I'm encountering an issue related to the order of my functions and I can't figure out the reason behind it. When I hover over the call for function_2 inside the first function, VSCode shows me the result as Promise<void>, and the console p ...

Update the value of the following element

In the table, each row has three text fields. <tr> <td><input type="text" data-type="number" name="qty[]" /></td> <td><input type="text" data-type="number" name="ucost[]" /></td> <td><input ty ...

Error alert: Controllers and services within the same module are experiencing injection issues

I'm in the process of creating an angular module that contains controllers and a service all within the same module. The issue I'm facing is an unknown provider error Error: $injector:unpr. I have made sure not to redefine the module multiple tim ...

Combine two arrays and collapse one of the nested elements

I need help merging two arrays based on ID and flattening one of the objects. I haven't been able to find a solution for my specific case. This is what I'm attempting and what I've managed to achieve so far: const a = { someProperty: &a ...