Angularjs map array to another array

后端 未结 4 1725
忘了有多久
忘了有多久 2021-01-15 14:18

I have two arrays, Users and Employments like so:

Users       = [{id:1, name: \"ryan\"}, {id:2, name:\"Julie\"}]
Employment         


        
4条回答
  •  無奈伤痛
    2021-01-15 14:56

    If you want the employee name to get displayed based on id, the simplest way is just pass that id to a function and return the name, like as shown below

    Working Demo

    html

  • {{getEmployeeName(employment.user_id)}}
  • 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 embed the User array in the Employments array, try the following stuff

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

    code for flattening Employments array by adding User properties

    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" } 
                         ]
    

    Working Demo

    UPDATE 3

    Code for making a nested employee structure like as shown below from $scope.Users and $scope.Employments

    $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" } } 
    ]
    

    Working Demo

提交回复
热议问题