Reputation: 845
I'm new to AngularJS and I'd like to build an object
with data from a json
file.
This is my json
file:
[
{"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
. 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. Just 1: Object 2: Object 3: Object ...
I know that the query for true or false is missing. But I want to fix this step before adding a query.
Upvotes: 1
Views: 4715
Reputation: 3856
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);
Upvotes: 1
Reputation: 382
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
$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.
$scope.submit = function(message,title){
var tempArr = ($scope.users).filter(function(d){
return (d.select == true);
});
});
console.log(tempArr)
Upvotes: 3
Reputation: 863
Try this one
var tempArr = [];
angular.forEach($scope.users, function(user){
user.select && tempArr.push(user.name);
});
console.dir(tempArr);
Upvotes: 1
Reputation: 8325
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
});
Upvotes: 0
Reputation: 17299
try this
$scope.submit = function(message,title){
var tempArr = [];
angular.forEach($scope.users, function(user){
tempArr.push( {"name":user.name} );
});
Upvotes: 1