AngularJS将数组映射到另一个数组

编程入门 行业动态 更新时间:2024-10-09 17:21:22
本文介绍了AngularJS将数组映射到另一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个数组,分别是用户和就业:

I have two arrays, Users and Employments like so:

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

我想以ng-repeat的形式显示Jobs数组:

I'd like to display the Employments array in an ng-repeat like so:

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

如何将用户"数组映射到就业"数组?

How do I map the Users array to the Employments array?

推荐答案

如果您希望根据id显示员工姓名,最简单的方法是将该id传递给函数并返回姓名,如下所示

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

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

脚本

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; } }; }; });

更新2

如果要在就业"数组中嵌入User数组,请尝试以下操作

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; } }); });

输出

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

工作演示

Working Demo

更新3

如下所示从$scope.Users和$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); });

输出

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

工作演示

Working Demo

更多推荐

AngularJS将数组映射到另一个数组

本文发布于:2023-11-25 21:09:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631355.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   AngularJS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!