Tips for implementing orderBy and filter in ng-repeat when working with an object instead of an array

I am facing a data structure that looks like this:

$scope.people = {
        "ID123": {
            name_de: "Andre",
            name_en: "Anrew",
            age: 30,
            description: "He is the father of xyz and . . .",

             . . .

        },
        "IDabc": {
            name_de: "Markus",
            name_en: "Mark",
            age: 20,

             . . .
        },
        "IDxyz": {
            name_de: "Isaak",
            name_en: "Isaac",
            age: 23,

             . . .
        }

    . . .

}

and I have an input/ng-repeat:

<input ng-model="query" placeholder="Search . . .">
<ul>
    <li ng-repeat="person in people | orderBy:'name_de' | filter:query"> Some output here . . . </li>
</ul>

The question now is how can I effectively order and filter this data?

I previously managed with an Array of persons, but I require the unique "ID's" which makes using objects necessary!?

Additionally, I am searching for a method to filter the object based on multiple properties, such as name_de AND name_en (so it will display ID123 if the search term is Andre or Andrew) WHILE disregarding the "description" property (initially the problem was that the filter checked all properties)

Answer №1

If you're looking to enhance your Angular skills, consider exploring the toArrayFilter module. You can find more information about it here.

For a hands-on experience, check out this sample demo of how to use the filter here:

angular.module('angular-toArrayFilter', [])

.filter('toArray', function () {
  return function (obj, addKey) {
    if (!(obj instanceof Object)) {
      return obj;
    }

    if ( addKey === false ) {
      return Object.values(obj);
    } else {
      return Object.keys(obj).map(function (key) {
        return Object.defineProperty(obj[key], '$key', { enumerable: false, value: key});
      });
    }
  };
});

var app = angular.module('app', ['angular-toArrayFilter']);

app.controller('firstCtrl', function($scope){

  $scope.persons = {

    "IDabc": {
            name_de: "Markus",
            name_en: "Mark",
            age: 20,


        },
        "ID123": {
            name_de: "Andre",
            name_en: "Anrew",
            age: 30,
            description: "He is the father of xyz and . . .",



        },

        "IDxyz": {
            name_de: "Isaak",
            name_en: "Isaac",
            age: 23,


        }   

};

});

html:

body ng-app="app">
  <div ng-controller="firstCtrl">
<input ng-model="query" placeholder="Suche . . .">
<ul>
    <li ng-repeat="p in persons | toArray | orderBy:'age' | filter:query"> {{p.name_de}} -> {{p.name_en}} </li>
</ul;
     </div>
   </body>

Answer №2

Regarding your inquiry,

I was able to use an Array of persons, but I require the "ID's", hence the necessity for objects!?

Could you please add ID as a property to your person objects so they appear like this?

$scope.persons = [
    { id: "ID123",
      name_de: "Andre",
      name_en: "Anrew",
      age: 30,
      description: "He is the father of xyz and . . .",
      . . .
    },
    { id: "IDabc",
      name_de: "Markus",
      name_en: "Mark",
      age: 20,
    },
         . . .
];

If you want to search by name_de AND name_en (or any other properties), you can create a custom filter. It's quite simple.

var app = angular.module("YourApp");
app.filter('MyCustomFilter', function(){
    return function(objects, criteria){
        if(!criteria)            
            return objects;

        var filterResult = new Array();
        for(var index in objects)
            if(objects[index].name_de.indexOf(criteria) != -1 || objects[index].name_en.indexOf(criteria) != -1)
                filterResult.push(objects[index]);
        return filterResult;
    }
});

Your HTML code will resemble this:

<input type="text" data-ng-model="personFilter" />
<div data-ng-repeat="person in persons | MyCustomFilter:personFilter"> ... </div>

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

Leverage JavaScript Object Properties within Angular 5 Components

Here's a question I have on using ngx-charts in Angular 5. I am experimenting with ngx-charts to create a chart within my Angular 5 project. The code snippet for my component is shown below: import { Component, OnInit } from '@angular/core&ap ...

Is there a way to showcase my information on flash cards using JavaScript?

Currently, I am developing a full stack application that utilizes JavaScript on both the front and back end. This application allows users to create their own flashcards set. Upon clicking "View Cards," the data is fetched and the question-answer pair is d ...

The disappearance of the "Event" Twitter Widget in the HTML inspector occurs when customized styles are applied

Currently, I am customizing the default Twitter widget that can be embedded on a website. While successfully injecting styles and making it work perfectly, I recently discovered that after injecting my styles, clicking on a Tweet no longer opens it in a ne ...

Best practices for building an Ember frontend and Node backend application

I'm currently working on a project that involves an ember frontend and a node backend. Within my ember-cli app, I've configured the .ember-cli file to proxy requests to node like this: { "proxy": "http://localhost:3000" } I've had to es ...

Adding items to an array within a jQuery each loop and performing a jQuery ajax request

I am trying to loop through an array, push the results into a JavaScript array, and then access the data outside of each loop and AJAX call. Can anyone explain how to do this? This is what I have attempted: var ides = ["2254365", "2255017", "2254288", ...

Unable to transmit an object using ExpressJS

Greetings. I am currently trying to comprehend ExpressJS. My goal is to send a simple object from the express server, but it only displays "cannot get" on the screen. app.get("/", (req, res, next) => { console.log("middleware"); const error = true; ...

The file import is restricted based on the user's input

I am facing an issue with my small vue.js app. My goal is to import a specific json file based on user input. import content from "@/posts/posts/" + new URL(location.href).searchParams.get('id') + ".json"; Every time I attem ...

Executing a function to erase the stored value in local storage during an Angular unit test

Looking to verify whether the localStorage gets cleared when I execute my function. Component ngOnInit() { // Logging out when reaching login screen for login purposes this.authService.logout(); } authService logout() { // Removing logged i ...

Is it possible to manipulate CSS on a webpage using javascript?

I have incorporated this piece of JavaScript to integrate a chat box onto my website: window.HFCHAT_CONFIG = { EMBED_TOKEN: "XXXXX", ACCESS_TOKEN: "XXXXX", HOST_URL: "https://happyfoxchat.com", ASSETS_URL: "https://XXXXX.cloudfront.ne ...

What is the best way to eliminate all whitespace in AngularJS binding strings?

I attempted the following: <div id="{{mystring.replace(/[\s]/g, \'\')}}"></div> However, it does not appear to be functioning as expected. The "mystring" object is located on the $scope and contains a string such as " ...

Error encountered when accessing JSON data from the DBpedia server in JavaScript

Hello everyone and thank you for your help in advance. I have encountered this error: Uncaught SyntaxError: Unexpected identifier on line 65 (the line with the "Var query", which is the third line) and when I click on the Execute button, I get another e ...

Can you explain the contrast between 'depict' and 'examine' when using Jest?

I am currently diving into the world of unit testing in Vue.js with Jest. One question that keeps popping up is when to use describe and when to use test ? TodoApp.vue Component : <template> <div> <h1>TodoApp Componenent</h1> ...

What are the best practices for utilizing ngMousedown effectively?

I've been attempting to capture the ngMousedown event without success. After searching online for a solution, I still haven't found what I'm looking for. Check out this jsfiddle snippet. I've also tried using mouseup and click events. ...

How does the 'this' variable function when it comes to models in embedded documents?

Being relatively new to node.js and sails, I find it quite easy to work with and enjoy it :) Currently, I am using the sails Framework version 0.10rc3 with MongoDB and sails-mongo. I understand that the contributors of waterline do not particularly like e ...

Increasing the Efficiency of Styled Components

It appears to me that there is room for improvement when it comes to checking for props in Styled Components. Consider the following code: ${props => props.white && `color: ${colors.white}`} ${props => props.light && `color: ${c ...

AngularJS framework may encounter an issue where changes in $scope data do not reflect in the view

I have noticed that when I reload the data using my function, the view does not change. After some research, I found that adding $scope.$apply() should solve this issue. However, I am encountering an error when trying to implement this solution. https://d ...

Managing state with Apollo within a component

Greetings and thank you for taking the time to help me out. I am currently diving into the world of Apollo and React, but it seems like I am struggling with some logic here. On my main page index.js, I have initialized Apollo in the following way: export c ...

leveraging jQuery mobile for asynchronous requests

I've been attempting to print a jQuery mobile element using ajax, but I'm running into an issue where the result isn't being encoded as jQuery mobile is intended to do. Below is a simplified excerpt of the JavaScript code responsible for t ...

How can I conceal the element that came before in JavaScript?

<div onclick="toggleContent(this)" class="iptv"><div class="triangle"></div><b>LUZ HD</b> - 98 channels (including 32 HD channels) <div class="iptv_price"><b><img src="img/rj45.png" class="icon_ofert ...

Turning off v-navigation-drawer for certain routes in Vue.js

I currently have a v-navigation-drawer implemented in my webpage using the code below in the App.vue file. However, I am looking to disable it on certain routes, such as the landing page: <v-app> <v-navigation-drawer id ="nav" persistent : ...