Mapping an array to another array using AngularJS

I am working with two arrays - Users and Employments. Here is how they are structured:

Users       = [{id:1, name: "ryan"}, {id:2, name:"Julie"}]
Employments = [{user_id: 1, title: "manager"}, {user_id: 2, title: "Professor"}]

My goal is to display the Employments array using ng-repeat in the following way:

<li ng-repeat="employment in Employments">
  {{employment.user.name}}
</li>

Can someone help me understand how I can map the Users array to the Employments array?

Answer №1

To display the employee name based on id, you can simply pass the id to a function and return the corresponding name. Here's how:

See Working Demo

html

<div ng-app='myApp' ng-controller="ArrayController">
    <li ng-repeat="employment in Employments">{{getEmployeeName(employment.user_id)}}
    </li>
</div>

script

var app = angular.module('myApp', []);
app.controller('ArrayController', function ($scope) {
    $scope.Users = [{
        id: 1,
        name: "ryan"
    }, {
        id: 2,
        name: "Julie"
    }];

    $scope.Employments = [{
        user_id: 1,
        title: "manager"
    }, {
        user_id: 2,
        title: "Professor"
    }];

    $scope.getEmployeeName = function (empId) {
        for (var i = 0; i < $scope.Users.length; i++) {
            if ($scope.Users[i].id === empId) {
                return $scope.Users[i].name;
            }
        };
    };
});

UPDATE 2

If you want to include User properties in the Employments array, follow this approach:

$scope.Users = [{id: 1, name: "ryan"}, {id: 2, name: "Julie"}];

$scope.Employments = [{user_id: 1, title: "manager"}, 
                      {user_id: 2, title: "Professor"}
                     ];

Code for combining User properties with Employments array

angular.forEach($scope.Users, function (user, userIndex) {
    angular.forEach($scope.Employments, function (employee, employeeIndex) {
        if (employee.user_id === user.id) {
            employee.name = user.name;
        }
    });
});

Output

$scope.Employments = [ { user_id: 1, title: "manager", name: "ryan" }, 
                       { user_id: 2, title: "Professor", name: "Julie" } 
                     ]

See Working Demo

UPDATE 3

Convert $scope.Users and $scope.Employments into a nested employee structure as shown below

$scope.employees = [];
angular.forEach($scope.Employments, function (employee, employeeIndex) {
    var employeeObject = {};
    employeeObject.title = employee.title;
    angular.forEach($scope.Users, function (user, userIndex) {
        if (employee.user_id === user.id) {
            employeeObject.user = user;
        }
    });
    $scope.employees.push(employeeObject);
});

Output

[ { title: "manager", user: { "id": 1, "name": "ryan" } }, 
  { title: "Professor", user: { "id": 2, "name": "Julie" } } 
]

See Working Demo

Answer №2

If you were looking to align the contents of two arrays using a template, you could utilize the following arrays

Users       = [{id:1, name: "ryan"}, {id:2, name:"Julie"}]
Employments = [{user_id: 1, title: "manager"}, {user_id: 2, title: "Professor"}]

Then implement a nested loop like this:

    <li ng-repeat="employment in Employments">
      <div ng-repeat="user in Users" ng-if="user.id === employment.user_id" >
        {{user.name}}:{{employment.title}}
      </div>
    </li>

Another helpful technique to prevent delays and unwanted symbols from displaying on your page is to use ng-bind and prefix attributes with data according to HTML specifications

        <li data-ng-repeat="employment in Employments">
          <div data-ng-repeat="user in Users" data-ng-if="user.id === employment.user_id" >
            <span data-ng-bind="user.name"></span>:<span data-ng-bind="employment.title"></span>
          </div>
        </li>

Even though you may only require the names, demonstrating how to incorporate the outer loop within the inner loop can still be beneficial. This concept also applies when using ng-init to reference the $index of the outer ng-repeat within the inner loop, but that may exceed the scope of what you're seeking.

Answer №3

Plunker

This function organizes the names of users into the employments array:

var organizeUsers = function() {
  var index = 0;
  for (index; index < $scope.users.length; index++) {
    console.log($scope.users[index].id)
    for(var j = 0; j < $scope.employments.length; j++) {
      if($scope.employments[j].user_id === $scope.users[index].id) {
        $scope.employments[j].name = $scope.users[index].name;    
      }
    } 
  }
}

HTML:

<ul>
      <li ng-repeat="employment in employments">
  {{employment.name}}
      </li>
</ul>

Answer №4

Yesterday, I encountered a similar issue. If you choose to utilize JavaScript, you will need to iterate through the loop twice. I suggest the most efficient approach would be to select all necessary data in a single query by joining tables if the data is coming from the same database.

You can retrieve User information with one query and Employment details with another query in the database. Then, iterate twice to organize them accordingly. Below is my proposed solution:

select users.*, employments.title from `users` inner join `employments` where users.id = employments.user_id; 

I hope this solution proves to be useful.

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

AngularJS Routing misinterprets hash href from jQuery UI Datepicker

This issue is a result of my own oversight. I neglected to properly initialize the model for the datepicker, causing jQuery UI to prevent the navigation event from firing. If you're encountering this same problem, chances are there's another mist ...

Determine the size of an SVG while taking into consideration any strokes applied

Is there a way to seamlessly position an SVG in the corner of a div, despite having a dynamically generated stroke? Calculating the distance to the outermost part of the border proves difficult when dealing with irregular shapes like stars. Here's my ...

Tips for transferring information from Javascript to a PHP script

For the code in JavaScript that I have written to transfer data to PHP, I am encountering an issue where it doesn't seem to work properly. Here is the code snippet: function codeAddress() { var address = document.getElementById('address') ...

Modifying a table row in real-time with the power of JQuery/JavaScript

I successfully created a table with a for loop in Java Spring and now I'm trying to dynamically show and hide specific parts of it when a button is clicked. Here's a simplified version of what I have: <jsp:attribute name= "scripts"> ...

Steps to interact with the gridview control in a usercontrol using a javascript function

In an attempt to access a user control from a JavaScript method and locate the gridview within that control to determine the number of checkboxes checked on the gridview, I encountered an issue. When trying to obtain the ID of the gridview from the usercon ...

I keep encountering an Uncaught SyntaxError: Unexpected token < error in my bundle.js file

Currently, I am in the process of creating a boilerplate for React web applications. However, whenever I try to access http://localhost:8080/, I encounter an error stating: Uncaught SyntaxError: Unexpected token < in my bundle.js file. I'm unsure ...

Limit the rotation of jQuery and CSS3 elements to always turn in a clockwise direction

Utilizing the jQuery transit plugin, I am rotating a block element with 4 navigation controls. Each time a nav item is clicked, the block rotates to the specified custom data attribute of that nav item - either 0, 90, 180, or 270 degrees. While I have suc ...

Using a for loop in JavaScript to dynamically display TextBoxFor(model=> model[i].prop) in an MVC application

I need some help getting this code to function correctly: $('#ddl').change(function () { $('#cont').html(''); var count = getCount($('#ddl').val()) for (var i = 0; i < count ; ...

Can JQuery be used to specifically target attributes with vendor prefixes?

Is there a way to change the Thumb color for my slider without needing to select the thumb with a vendor prefix? I want to be able to dynamically pick the color without simply appending a class. $('.button').on('click', function (e) { ...

Prevent the reloading of the page by utilizing Ajax technology when submitting a form in Laravel

I'm facing a challenge with processing a form submit using ajax instead of Laravel to prevent page reloads. Unfortunately, it's not working as expected and I'm struggling to figure out the issue. Despite researching numerous examples online, ...

Using JavaScript to create an object from a JSON data set

Currently, I am working on a TestComplete (UI testing) project that involves JavaScript. In an attempt to store class references in JSON, I have encountered issues with my code not functioning as expected. This has led me to suspect that there may be a mis ...

Selecting a value will cause other blocks to vanish

How do I hide other filter buttons when I select a value? Check out my code snippet below: const FilterBlock = props => { const { filterApi, filterState, filterFrontendInput, group, items, name, ...

Failed to convert the value "hello" to an ObjectId (string type) for the _id path in the product model

i am currently using node, express, and mongoose with a local mongodb database. all of my routes are functioning correctly except for the last one /hello, which is giving me this error: { "stringValue": "\"hello\"&qu ...

AngularJS Issue [$injector:modulerr]

My AngularJS module, developed following these tutorials, is not working properly in conjunction with ASP.NET MVC. I have encountered an error [$injector:modulerr] and I am unsure of how to resolve it. (function () { var AAngScript = angular.module(&a ...

Back to the same old Safari antics - forms submitting without going through AJAX

Feeling frustrated as my brain can't seem to figure out what's wrong with Safari. While all other browsers are working perfectly, Safari refuses to read my JavaScript code. It won't even display a simple 'alert()'. Any ideas? ==== ...

Encountered an issue with npm install showing error message 'Failed: connection closed unexpectedly.'

Encountered an issue while running the command npm install module-name --save. The installation fails regardless of the module I try to install. Even specifying it in the package.json and then running npm install for the entire project results in failure ...

Calculate the values for top, left, width, and height in a Three.js projection

I'm currently facing an issue: I am trying to position a DIV on top of a WebGL animation. The scenario involves rotating a `mesh` using a `PlaneGeometry` to fill a rectangular area, and then placing the DIV at the top of that space. To achieve this, I ...

Having issues with the Bootstrap popup model functionality on my website

I am facing an issue with the Bootstrap popup not displaying correctly on my website. I utilized the code directly from the official Bootstrap website for the popup implementation. You can find my website at this link: Link to webiste The placement of th ...

Ways to get the most out of your list while working within a budget constraint

In my possession are 5 different collections: Collection 1: ['a', 21, $17], ['b', 19, $14], ['c', 17, $13], ['d', 16, $13] Collection 2: ['e', 19, $14], ['f', 16, $12], ['g', 14, $12], ...

Verify that the text entered in the form is accurate, and if it meets the required criteria, proceed to the next

Is it possible to achieve this without using JavaScript? If not, I'd like to find the simplest solution. I have a form that functions similar to a password entry field, and I would like to redirect users to a certain page if they type in a specific p ...