nytez nytez - 3 months ago 14
AngularJS Question

Angular filter string array by object value

I have two arrays.
First is

$scope.termini
which contains string, and other one is
$scope.reserved
which contains objects. Each of objects has variable
vrijemeTermina
. I want to filter
$scope.termini
by
$scope.reserved[x].vrijemeTermina
.

reserve.controller('resCtrl', function($scope, $http) {
$scope.$watch("pickedDate", function(){
$scope.termini=["13:00","15:00","17:00","19:00","21:00"];
$http.post('php/dropdown.php',{"datum":$scope.pickedDate}).success(function(data){
$scope.reserved = data;
//alert(JSON.stringify(data));
//alert($scope.reserved[0].datumTermina);
angular.forEach($scope.reserved, function(value, key){
$scope.termini = $filter('filter')($scope.termini, value.vrijemeTermina, false);
});
});
console.debug("%o", $scope.termini);
});
});


I tried so many things that didn't work. Most answers I found filter object arrays by it's property. I didnt find a solution for this problem yet.

<?php
require_once(dirname(dirname(__FILE__))."/php/db-conn.php");

$data = json_decode(file_get_contents("php://input"));

$query = "SELECT * from termin WHERE datumTermina='".$data->datum."'";
$result = mysqli_query($con, $query);
$arr = array();
if(mysqli_num_rows($result) != 0) {
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
}

$con->close();

echo json_encode($arr);

?>


Thats my php file. It returns json that looks like
{0:{"id":"1";"vrijemeTermina":"13:00";"datumTermina":"03/09/2016"}}
I guess.

Answer

Try this:

$scope.termini = $scope.reserved.filter(function(v){
   return $scope.termini.filter(function(e){
              return e == v.vrijemeTermina
            }).length > 0;
});

This will create an array with all the objects from $scope.reserved that have their vrijemeTermina value equal to one of the values from the original $scope.termini array.

Oh, I've read you're question again and I think your want this to work the other way around.

$scope.termini = $scope.termini.filter(function(v){
   return $scope.reserved.filter(function(e){ 
              return e.vrijemeTermina == v
            }).length > 0;
});