gpt4 book ai didi

javascript - 以 Angular 链接两个对象

转载 作者:行者123 更新时间:2023-11-29 17:53:52 24 4
gpt4 key购买 nike

我有2个数据集

帖子

[
{
"postId": 1,
"postContent": "Lorem Ipsum",
"user": 1
},
{
"postId": 2,
"postContent": "Lorem Ipsum",
"user": 2
},
]

和用户

[
{
"user": 1,
"firstName": "John",
"lastName": "Doe"
},
{
"user": 2,
"firstName": "Johny",
"lastName": "Doey"
}
]

我正在重复所有帖子,我想通过 $scope.post.user.firstName 等访问用户数据。

我应该怎么处理它?<​​/p>

最佳答案

您可以使用 Array.prototype.find() 实现类似 getUserById() 的方法在遍历您的帖子时使用它。

AngularJS 中的代码:

angular
.module('App', [])
.controller('AppController', ['$scope', function ($scope) {
$scope.posts = [{"postId": 1,"postContent": "Lorem Ipsum","user": 1},{"postId": 2,"postContent": "Lorem Ipsum","user": 2}];
$scope.users = [{"user": 1, "firstName": "John", "lastName": "Doe"},{ "user": 2, "firstName": "Johny", "lastName": "Doey"}];

$scope.getUserById = function (id) {
return $scope.users.find(function (user) {
return id === user.user;
});
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>

<div ng-app="App" ng-controller="AppController" class="row">
<div ng-repeat="p in posts">
<p>{{p.postContent}} <i>by {{getUserById(p.user).firstName}}</i></p>
</div>
</div>

关于javascript - 以 Angular 链接两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40936397/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com