Filtering a string array in Angular based on an object's value

I am facing a challenge with two arrays in my code. The first array, $scope.termini, contains strings, and the other one, $scope.reserved, contains objects. Each object in the second array has a variable called vrijemeTermina. My goal is to filter $scope.termini based on the values of

$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 have tried multiple approaches to solve this issue without success. Most solutions I come across involve filtering object arrays based on their properties, but I have not yet found a suitable solution for my specific problem.

<?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);

?>

This is my PHP file that returns JSON data in the format

{0:{"id":"1";"vrijemeTermina":"13:00";"datumTermina":"03/09/2016"}}
as far as I can tell.

Answer №1

Give this a try:

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

This code snippet will generate an array containing objects from $scope.reserved that have their vrijemeTermina value matching one of the values in the original $scope.termini array.

Upon reviewing your question again, it seems like you want it to work the opposite way.

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

Answer №2

Would you consider a purely JavaScript approach, utilizing the filter() method?

$scope.termini.filter(function(element, index, array) {

    return element == $scope.reserved[index].vrijemeTermina;

});

Do you think this solution meets your needs? It generates an array containing all elements from $scope.termini where the corresponding value in

$scope.reserved[i].vrijemeTermina
, based on the index, matches. If this isn't the desired outcome, could you provide more clarity on what you are trying to achieve?

Answer №3

To access the property named vrijemeTermina of each object within a for loop, you can use the following code snippet:

reserve.controller('resCtrl', function($scope, $http, filterFilter) {

    $scope.$watch("pickedDate", function() {

        $scope.termini = ["13:00","15:00","17:00","19:00","21:00"];

        $http.post('php/dropdown.php',{"datum":$scope.pickedDate})
        .then(function(response) {

            // ensure proper data parsing
            $scope.reserved = angular.fromJson(response.data);

            // check if the data is in array format
            if (!angular.isArray($scope.reserved)) {
                console.error("Expected $scope.reserved to be an Array but found type: " + typeof($scope.reserved));
                return;
            }

            // iterate through the array of objects
            for (var i = 0; i < $scope.reserved.length; i++) {

                // filter $scope.termini based on the current object's vrijemeTermina value in each iteration
                $scope.termini = filterFilter($scope.termini, $scope.reserved[i].vrijemeTermina, false);

            }

            console.debug("%o", $scope.termini);

        }, function(error) {

            // handling errors is good practice

        });

    });

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When a user clicks a button, modify a section of the URL and navigate to

I've been searching everywhere for a solution to this issue, but I just can't seem to find it. I'm hoping someone here can help me out. In a bilingual store, I need a way to redirect users to the same product on a different domain when they ...

"Attempt to create angular fork results in an unsuccessful build

I have recently created a fork of angularJs and I am facing an issue when trying to build it. The build process fails when running grunt package npm -v --> 3.5.2 bower --version --> 1.7.2 I followed the steps provided in the official documentation ...

The function you are trying to call is not callable. The type 'Promise<void>' does not have any call signatures. This issue is related to Mongodb and Nodejs

Currently, I am attempting to establish a connection between MongoDB and Node (ts). However, during the connection process, I encountered an error stating: "This expression is not callable. Type 'Promise<void>' has no call signatures" da ...

Accepting a custom object wrapper containing non-primitive attributes in Spring MVC using @RequestBody

To create the JSON data, I followed these steps: var manager = { username: "admin", password: "admin" }; var userToSubscribe = { username: "newuser", password: "newpassword", email: "<a href="/cdn-cgi ...

When trying to access the page via file://, the cookies are not functioning properly

My HTML code is functioning properly in Firefox and even on the W3Schools website when tested using their editor in Chrome. However, when I run my code in Chrome from Notepad++, it doesn't seem to work. It appears that the body onload event is not tri ...

Switching colors after uncovering text using JavaScript

I'm striving to achieve specific results with my code, but I'm having trouble pinpointing what exactly I'm doing wrong. Any guidance on how to correct my approach would be greatly appreciated. Currently, I've created rows that can be c ...

Looking to grasp the concept of calling inline functions within a React functional component

As a newcomer to React, I recently created a new view within my company. Following the example of many guides, I have utilized inline functions and function components exclusively. One common practice I have adopted is writing onClick events in this manne ...

To efficiently update several rows in a single query, we require input in the form of a JSON object containing multiple sets of data

update users as u set -- postgres FTW email = u2.email, first_name = u2.first_name, last_name = u2.last_name from (values (1, '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c14131010150f3c0b1915111d121 ...

The error message "404 Not Found" was triggered when attempting to deliver the

Here is the server-side code snippet that I am using: var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendfile( ...

Issue with Angular modal text boxes failing to populate using ngModel

I am facing an issue with populating data in a modal when a table row is clicked. The table contains TV show data and uses dir-paginate/ng-repeat to display the information. However, when I click on a row to edit the show, the ng-model data does not load i ...

Struggling to display Firestore data in a React component - useRef() does not trigger re-render and useState() throws an error

I am currently working on a project involving a React component called Dashboard. The component includes various features such as loading data from a Firestore database and displaying it on the page. While implementing this functionality, I encountered an ...

"Enhance Your Design with Hovering CSS Backgrounds

Seeking assistance with changing the background image on span hover. If anyone can assist, I have included the complete code for the website below. Take a look at the full website code here: Pastebin CSS Pastebin JavaScript ...

Overlap one element entirely with another

Currently, I am working on a way for an element called overlayElement to completely cover another element known as originalElement. The overlayElement is an iFrame, but that detail may not be significant in this scenario. My goal is to ensure that the over ...

Using Primeng to implement pagination and lazy loading in a dataView

Looking for a way to search through product data with filters and display it using primeng dataview? Consider implementing pagination in your API that pulls products from the database page by page. Set the products array as the value in dataview so that wh ...

Tips for integrating execute_script and WebDriverWait in Selenium automation

Is there a way to combine execute_script() and WebdriverWait? In my current code: network_list = driver.find_element_by_xpath('//*[@id="folder_box"]/div[1]/div/div[2]/div[1]') wait = WebDriverWait(driver, 4) try: wait_network_list = wait.unt ...

Replace the typical bootstrap text class with stylish and modern google material icons

As a newcomer to the world of javascript, I acknowledge that my approach may not be ideal... I'm attempting to modify the color of a material icon upon clicking it. Essentially, I want to toggle it on and off. The challenge lies in the code's in ...

The makeSVG function from GoJS is failing to generate the correct HTML SVG object

I have been utilizing the Diagram.makeSVG() method to create an SVG from my diagram. Subsequently, I appended the SVG to a new empty tab using this script (diagram represents my Diagram Object): function print() { var newTab = window.open(), svg ...

Rendering an object as a React child is not allowed (object found with keys {this}). To display multiple children, make sure to use an array instead of an object

Encountering an error: How can I resolve this issue in React? The file relates to the layout I am utilizing Visual Studio export default class Layout extends React.Component { constructor(props) { super(props); this.identify = this.identify.bi ...

Similar to Jquery ajax, Titanium also offers a powerful tool

Currently, I have been making an API call using Titanium in the following way: var url = "http://www.appcelerator.com"; var client = Ti.Network.createHTTPClient({ // callback when data is received onload : function(e) { Ti.API.info("Re ...

What could be causing the alteration of my JSON data when sent through a WEB.API Ajax request?

Before Ajax Call: "{ "UnitOfMeasureRelatedUnitDataInbound": [ { "Name": "test", "Active": true, "UnitOfMeasureTypeID": "dd89f0a0-59c3-49a1-a2ae-7e763da32065", "BaseUnitID": "4c835ebb-60f2-435f-a5f4-8dc311fbbca0", "BaseUnitName": null, ...