$http
.get('/getFollowings/' + currentUser)
.success(function(response) {
$scope.friendlist = response;
});
我想得到响应的数据。但我无法单独处理这些值。 '回应'包含:
[{"_id":"597c9fabc1ada32277f1da34","following":[{"username":"him"},{"username":"ron"},{"username":"nadu"}]}]
我希望得到usernames
。
答案 0 :(得分:2)
我建议使用lodash库,试试这个:
$scope.friendlist = _.chain(response.plain())
.map(function(item){
item.following = _.pluck(item.following,'username')
return item;
})
.pluck('following')
.flatten()
.value();
答案 1 :(得分:0)
您可以使用angular.forEach
$scope.usernames = [];
$http.get('/getFollowings/' + currentUser)
.success(function(response) {
$scope.friendlist = response;
angular.forEach($scope.friendlist[0].following, function(val) {
$scope.usernames.push(val.username)
});
});
此处$scope.usernames
是一个包含用户名
您可以使用ng-repeat
在视图中显示这些值。
var myApp = angular.module('myApp', []);
myApp.controller('ctrl', ['$scope', function($scope) {
var response = [{
"_id": "597c9fabc1ada32277f1da34",
"following": [{
"username": "him"
}, {
"username": "ron"
}, {
"username": "nadu"
}]
}];
$scope.usernames = [];
angular.forEach(response[0].following, function(val) {
$scope.usernames.push(val.username)
});
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
<div ng-repeat="username in usernames"><span>{{username}}</span></div>
</div>
答案 2 :(得分:0)
如果您使用$ http,则需要将Object提供给客户端。
结构:
{
"data": [
{
"_id": "597c9fabc1ada32277f1da34",
"following": [
{
"username": "him"
},
{
"username": "ron"
},
{
"username": "nadu"
}
]
}
]
}
在您的控制器中:
$scope.friendlist = response.data;
//i think it's simple
for(var i=0;i<$scope.friendlist.length;i++){
console.log($scope.friendlist[i]);
}
答案 3 :(得分:0)
只需使用forEach循环从阵列中获取所有用户名。
$scope.usernameList = [];
$http
.get('/getFollowings/' + currentUser)
.success(function(response) {
$scope.friendlist = response;
$scope.friendlist[0].following.forEach(function(item){
$scope.usernameList.push(item.username);
});
});
所以现在$scope.usernameList
包含名为以下数组的所有用户名。