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

Creating a dynamic dropdown menu using JQuery that does not automatically submit the form when a value is

Upon selecting a background color from the dropdown menu, I am generating a dynamic dropdown for text colors. The Text Color dropdown is populated correctly based on the selection of Background Color. Although the functionality works as intended, I encoun ...

WebPack Error: When calling __webpack_modules__[moduleId], a TypeError occurs, indicating that it is not a function during development. In production, an Invalid hook call error

Encountering a WebPack error when utilizing my custom library hosted as a package and streamed with NPM Link. Interestingly, the production version functions flawlessly. Below are my scripts: "scripts": { "dev": "rm -rf build ...

VueJS: Unable to access the 'name' property as it is undefined"

I'm at a loss trying to figure out a solution for this issue. My current task involves editing a pub schedule using an edit form: pubs/UpdateProfile.vue <template> <confirm title="Edit Pub" ok="Save pub" :show="show" v-on:save="sa ...

Find the nearest iframe relative to a parent element

I am attempting to find the nearest iframe element to a parent element in order to pinpoint the specific iframe that I want to customize using CSS: <div class ="accroche"> <iframe></iframe> <iframe></iframe> &l ...

Verify if the array entries match

Within my select element, I populate options based on an array of values. For example: [{ name: 'A', type: 'a', }, { name: 'B', type: 'b', }, { name: 'B', type: 'b', }, { name: &apos ...

Locate the div element containing specific text and remove the text from the

Is there a way to locate a div that contains specific text and remove only that specific text from the div? For instance: <div> DeleteText <span>Something text</span> <div>Something span inner text </div> </div> I am l ...

In ReactJs, what is the best way to load a new component when a button is clicked?

In ReactJs, I have developed a main component known as MainPage using Material-UI. import React from 'react'; import Grid from '@material-ui/core/Grid'; import Button from '@material-ui/core/Button'; import CssBaseline from & ...

Combining a name using JavaScript even if certain parts are not available

How can I efficiently combine name elements without any extra white space in Vue.js? let FirstName = "John" let MI = "G" let LastName = "Jones" let Suffix = "Jr." I want to create let fullName = "John G Jones Jr." However, in cases like this: let First ...

How can you retrieve the <head> content from a remote website without being able to make any changes to that site?

Imagine I need to access the <head> tag of a remote website like YouTube. Whenever I attempt this, I encounter an error message: Access to XMLHttpRequest at ‘Website I am trying to access for the head section’ from origin ‘My Website’ has b ...

Using conditional rendering within the map function in React

I am working with the code snippet below and I am looking to implement a conditional rendering to exclude index 0 from being displayed. How can I achieve this? return ( <section> {pokemonCards.map((pokemon, index) => ...

The feature of Access Control Request Headers involves appending certain information to the header of an AJAX request when using jQuery

Looking to enhance an AJAX POST request from jQuery with a custom header. Attempted solution: $.ajax({ type: 'POST', url: url, headers: { "My-First-Header":"first value", "My-Second-Header":"second value" } ...

Manipulating events through adjusting values of a JQuery-UI range-slider

My range-slider's values are being set with the code: $('...').slider( 'values', [ 0, 10000 ] );. However, I am facing an issue where this line triggers the change( event, ui ) event twice. Is there a way to ensure it only triggers ...

Comparing tick and flushMicrotasks in Angular fakeAsync testing block

From what I gathered by reading the Angular testing documentation, using the tick() function flushes both macro tasks and micro-task queues within the fakeAsync block. This leads me to believe that calling tick() is equivalent to making additional calls pl ...

Using Selenium: Checking for existing dropdown values and incrementing if necessary

I am currently working on automating an application using Selenium Webdriver with Java. The web application I am testing has an Add button that, when clicked, triggers the activation of a dropdown menu. Subsequent clicks on the Add button reveal additional ...

What purpose do controller.$viewValue and controller.$modelValue serve in the Angular framework?

I'm confused about the connection between scope.ngModel and controller.$viewValue/controller.$modelValue/controller.$setViewValue(). I'm specifically unsure of the purpose of the latter three. Take a look at this jsfiddle: <input type="text" ...

What is the process for defining custom properties for RequestHandler in Express.js middleware functions?

In my express application, I have implemented an error handling middleware that handles errors as follows: export const errorMiddleware = (app: Application): void => { // If the route is not correct app.use(((req, res, next): void => { const ...

Utilizing JavaScript Modules to Improve Decoupling of DOM Elements

Currently, I am tackling portions of a complex JavaScript application that heavily involves DOM elements. My goal is to begin modularizing the code and decoupling it. While I have come across some helpful examples, one particular issue perplexes me: should ...

Error encountered: Unable to locate module 'psl'

I'm encountering an issue when trying to execute a pre-existing project. The error message I keep receiving can be viewed in the following error logs image Whenever I attempt to run "npm i", this error arises and I would greatly appreciate it if some ...

What is the best way to combine a QR code and an existing image using Java script?

Looking for help in embedding a created QR code into an existing image. I am proficient in nodeJS, JavaScript, and jQuery. Any assistance would be greatly appreciated. ...

Display Rails view using JavaScript when clicked

I have a task to create a view where users can click on different buttons and see different content displayed based on the button they choose. I attempted to achieve this using JavaScript, but unfortunately, I couldn't get it to work as intended. Init ...