How can I filter an array by a nested property using Angular?

I need help with objects that have the following format:

id: 1,
name: MyObj
properties: {
  owners: [
  {
    name:owner1,
    location: loc1
  },
  {
    name:owner2,
    location: loc1
  }
 ]
}

Each object can have a different number of owners. I'm trying to filter these objects using ng-repeat with filter:searchBox and search box inputs

<input name="search-filter" class="form-control" type="search" ng-model="searchBox.properties.title" />
<input name="search-filter" class="form-control" type="search" ng-model="searchBox.properties.owners" />

The filtering works perfectly based on title, but for owners it doesn't seem to work at all, even though I expected it to filter using both location and name. Can someone please point out what I might be doing wrong?

Answer №1

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {

$scope.objs = 
  {
    id: 1,
    name: 'MyObj',
    properties: {
      owners: [
      {
        name: 'owner1',
        location: 'loc1'
      },
      {
        name: 'owner2',
        location: 'loc2'
      }
     ]
    }
  };

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">

<input name="search-filter" class="form-control" type="search" placeholder="Search by location" ng-model="searchBox.properties.location" />
<input name="search-filter" class="form-control" type="search" placeholder="Search by name"   ng-model="searchBox.properties.owners" />
 
  <div ng-repeat="owner in objs.properties.owners | filter:{'location': searchBox.properties.location} |filter:{'name': searchBox.properties.owners}">
    {{owner}}
    
  </div>

</div>

Answer №2

If you want to refine your search manually

var newList = [
  {
    id: 1,
    name: 'MyObj',
    properties: {
      owners: [
      {
        name: 'owner1',
        location: 'loc1'
      },
      {
        name: 'owner2',
        location: 'loc1'
      }
     ]
    }
  }
];

function filterResults(filterCriteria) {
  return newList.filter(function(item) {
    return item.properties.owners.find(function(owner) {
      return Object.keys(filterCriteria).every(function(key) {
        return filterCriteria[key] === owner[key];
      });
    });
  });
}

console.log(filterResults({ name: 'owner1', location: 'loc1' }));

I made use of es6 shim for this process.

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

While using jQuery, it was discovered that the name attribute could be changed within the .each() function when working in console.log. However

I'm attempting to modify the name attribute of a cloned table row with the following code: var ipCount = 2; $("#input_form").on("click", "#add_input_param", function() { $('#input_param tr').eq(1).clone().find('input').val ...

What is the best way to ensure that consecutive if blocks are executed in sequence?

I need to run two if blocks consecutively in TypeScript, with the second block depending on a flag set by the first block. The code below illustrates my scenario: export class Component { condition1: boolean; constructor(private confirmationServic ...

conditionally trigger one observable in rxjs before the other

I am in need of assistance or guidance regarding a challenge I am facing with rxjs that I cannot seem to resolve. In essence, my goal is to trigger an observable and complete it before the original one is triggered. Scenario: I am currently working on a ...

Ajax undoes any modifications enacted by JavaScript

When using ajax, I trigger an OnTextChangedEvent. Before this event occurs, there is a Javascript function that validates the input field and displays text based on its validity. However, once the Ajax is executed, it resets any changes made by the Javascr ...

I am experiencing difficulty in passing parameters to nested navigators

I have developed a TechInfo page and a ProfileInfo page. The ProfileInfo Page is nested inside a Drawer Navigator. I want to display some information from the TechInfo page and some from the ProfileInfo page when I enter our info and press a button. Howeve ...

AJAX POST request encountered a 400 Bad Request Error

One of the tasks in my Spring project is to enable data updating in the database upon clicking a specific button. Currently, I have the following code set up: update.jsp : <div class="searchParentOne"> <div class="noticeBlankTwoButtons ...

Trigger the fire controller code upon the change of the textbox date in ASP.NET MVC

I am looking for a way to trigger controller code when a user clicks out of a date textbox without using HTML helpers, only plain HTML. I am new to MVC and have previously worked with web forms. The controller code that needs to be executed is as follows: ...

I am having trouble establishing a connection between my Node.js server and the Google Cloud Platform server

I've been working on a global ESP32 Cam project, aiming for worldwide connectivity. I came across a tutorial that has been my guide: https://www.youtube.com/watch?v=CpIkG9N5-JM. I followed all the steps in the tutorial diligently, but unfortunately, I ...

Steps to efficiently enumerate the array of parameters in the NextJS router:

In my NextJS application, I have implemented a catch all route that uses the following code: import { useRouter} from 'next/router' This code snippet retrieves all the parameters from the URL path: const { params = [] } = router.query When I co ...

Warning: Attention Required for Published NPM Package Fix

After successfully publishing my first package on npm, I encountered a warning when I tried to import it in Codesandbox. There was an error converting '/node_modules/protected-react-routes-generators/src/index.js' from esmodule to commonjs: Canno ...

How to effectively utilize multiple Vue instances in your project?

My inquiry is somewhat linked to a similar question on Stack Overflow, but I am uncertain about the level of discouragement towards the approach discussed in relation to Vue. In my situation, I am working on a project where the DOM is generated entirely b ...

How can you direct a user to a specific page only when certain conditions are met?

Currently using React in my single page application. I have a good grasp on how Routes function and how to create a PrivateRoute. The issue arises when I need to verify the user's identity before granting access to a PrivateRoute. My attempt at imple ...

AngularJS: Changing color property using toggle when a CSS class is modified

After starting to learn AngularJS, I have been able to find many helpful answers on this forum. However, there is one particular issue that has been causing me frustration. My goal is to dynamically change the color property of an element only when it has ...

How to Retrieve URL Parameters in Gatsby

As I delve into learning React and Gatsby, I encountered an issue with my page containing URL parameters. Despite everything working smoothly on my local machine, after the gatsby build process, the variable url = undefined. How can I retrieve these para ...

Angular2 Error: Cannot have two identifiers with the same name, 'PropertyKey' is duplicated

I am currently developing an application with angular2 using angular-cli. Unfortunately, angular-in-memory-web-api was not included by default. After some research, I manually added the line "angular-in-memory-web-api": "~0.1.5" to my ...

StartsWith() function failing when used in conjunction with takeWhile()

I'm trying to iterate over an Immutable List and create a new list containing only the entries that start with a specific string. In this case, I want to find all states that begin with the letter 'D'. However, instead of returning a list wi ...

Determine the existence of a document/record in MongoDB

I am having trouble using .find({}) with MongoDB as it is not returning the expected response. I'm not sure how to determine if the document exists or not. What I want to achieve is: If a document exists, then do something - like sending a response b ...

`Welcome to the World of AngularJS with IntelliJ IDEA`

Hey there! I'm currently diving into the world of Angular.js and IntelliJ IDEA, but seems like I've hit a roadblock. I'm attempting to create a basic "hello world" example from a book in the IDE, but it's just not cooperating. After dow ...

I need help figuring out how to retrieve the full path of an uploaded file in JavaScript. Currently, it only returns "c:fakepath" but I need

Is there a way to obtain the complete file path of an uploaded file in javascript? Currently, it only shows c:\fakepath. The file path is being directly sent to the controller through jquery, and I need the full path for my servlet. Are there any alte ...

Loop through each item in the JSON object

After making an ajax call, I receive a json object in the success callback with the following structure: {test 1: Array(2), test 2: Array(3), test 3: Array(2)} The arrays inside each key have elements that look like this: 0: {IdProduct: "1", ProductName ...