[英]angularjs foreach loop issue
I'm new to AngularJS and I'd like to build an object
with data from a json
file. 我是AngularJS的新手,我想用
json
文件中的数据构建object
。
This is my json
file: 这是我的
json
文件:
[
{"id": 1, "name": "user1", "select": false },
{"id": 2, "name": "user2", "select": false },
{"id": 3, "name": "user3", "select": false },
{"id": 4, "name": "user4", "select": false },
{"id": 5, "name": "user5", "select": false }
]
And now I want to use foreach
loop to check which user has got select == true and push this username to new array
. 现在,我想使用
foreach
循环来检查哪个用户具有select == true并将此用户名推送到新array
。 So here is my first Try: 所以这是我的第一个尝试:
'use strict';
angular.module('apiOmat', [])
.controller('UsersCtrl', function($scope, $http){
$http.get('users.json').then(function(usersResponse) {
$scope.users = usersResponse.data;
});
$scope.submit = function(message,title){
var tempArr = [];
angular.forEach($scope.users.name, function(value,key){
tempArr.push(value);
});
console.log(tempArr);
$scope.messagebody = '{ "title" = "' + title + '", "message" = "' + message + '"}';
}
});
I also tried this: 我也试过这个:
$scope.submit = function(message,title){
var tempArr = [];
angular.forEach($scope.users, function(value,key){
tempArr.push( { key : value } );
});
console.log(tempArr);
The Console logs the 5 object, but without any value. 控制台记录5个对象,但没有任何值。 Just 1: Object 2: Object 3: Object ...
只是1:对象2:对象3:对象...
I know that the query for true or false is missing. 我知道对真或假的查询丢失了。 But I want to fix this step before adding a query.
但是我想在添加查询之前修复此步骤。
For this: 为了这:
And now I want to use a foreach-loop to check which user has got select == true and push this username to my new array
现在我想使用一个foreach循环来检查哪个用户具有select == true并将此用户名推送到我的新数组
$scope.submit = function(message,title){
var tempArr = [];
angular.forEach($scope.users, function(item){
if( item.select == true){
tempArr.push(item);
}
});
Another simple & better solution is to use filter
instead. 另一个简单且更好的解决方案是改为使用
filter
。
$scope.submit = function(message,title){
var tempArr = ($scope.users).filter(function(d){
return (d.select == true);
});
});
console.log(tempArr)
try below 尝试下面
$scope.submit = function(message,title){
var tempArr = [];
angular.forEach($scope.users, function(i,j){
if(i.select == true)
{
tempArr.push( i.name );
}
});
console.log(tempArr);
try this 尝试这个
$scope.submit = function(message,title){
var tempArr = [];
angular.forEach($scope.users, function(user){
tempArr.push( {"name":user.name} );
});
Try this one 试试这个
var tempArr = [];
angular.forEach($scope.users, function(user){
user.select && tempArr.push(user.name);
});
console.dir(tempArr);
Keep it simple: 把事情简单化:
$scope.submit = function(message, title){
var tempArr = [];
angular.forEach($scope.users, function(user){
if( user.select == true) //filter select:true only
tempArr.push( {"name_as_key":user.name} ); //name_as_key can be replaced if intended to
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.