Filtering objects by their properties or attributes in AngularJS can be achieved by using forEach, but encountering an error stating "forEach is

In my AngularJS application, I have a page that displays multiple widgets. One widget shows a table with details about a monitored system. Currently, the table has two columns: 'Type' and 'Data', displaying information and values respectively.

To customize the widget's display, users can click the 'Settings' button to open a dialog. In this dialog, they can input column headings and rows for the table. When typing in the 'Rows' field, a dropdown appears with available variables matching the user's input.

The function responsible for the dropdown is:

$scope.autocompleteVarsFilter = function(query) {
    if(!query && lastVarQryKw) {
        query = lastVarQryKw;
    }
    var result = Object.keys(fxVar.getVars()).filter(function(name) {
        return name.indexOf(query.toLowerCase()) !== -1;
    });

    if(result.length > 0) {
        lastVarQryKw = query;
    }
    return result;
};

I want to add a third column to the table that will contain links chosen by the user. These links are denoted by strings starting with :. The goal is to show all available pages when a user types : followed by filtering based on their input.

I updated the function as follows:

$scope.autocompleteVarsFilter = function(query) {
    if(query.startWith(":") {
        var buttonsQuery = query.substring(1);
        if(!buttonsQuery && lastVarQryKw) {
            buttonsQuery = lastVarQryKw;
        }

        var userPages = pagesPresets;
        console.log("Value of userPages: ", userPages);

        var page;
        for(page in userPages) {
            console.log("for loop started");
            if(page.key.startWith(buttonsQuery)) {
                console.log("Matching page found: ", page);
            }
        }

        if(result.length > 0) {
            lastVarQryKw = query;
        }
        return result;

    } else {
        if(!query && lastVarQryKw) {
            query = lastVarQryKw;
        }
        var result = Object.keys(fxVar.getVars()).filter(function(name) {
            return name.indexOf(query.toLowerCase()) !== -1;
        });

        if(result.length > 0) {
            lastVarQryKw = query;
        }

        return result;
    }
};

After testing, I encountered an issue where the pages weren't displayed in the dropdown when typing :. Console output showed a TypeError related to accessing the 'key' attribute of userpage objects.

I attempted different solutions like using forEach loops, but none resolved the issue. Anyone have suggestions?

Answer №1

When using a for...in loop, you are iterating through the enumerable property names of an object. To access the corresponding value, you need to use that property name. Here's an example:

console.log('Using for...in on an object:');

var myObj = {
  'prop1': 'Hello world!',
  'prop2': 12345,
  'some crazy property': null
};

for (var propName in myObj) {

  console.log('propName is ' + propName);

  //Accessing the value using the property name.
  var propValue = myObj[propName];

  console.log('myObj[' + propName + '] is ' + propValue);

}

In contrast, with a forEach loop, you directly iterate over the values in an array. Your callback function receives the value directly without needing to access the array. Here's an example:

console.log('Using forEach on an array:');

var myArray = [
  {key: 'this is object 1!'},
  {key: 'this is object 2!'}
];

myArray.forEach(function (obj) {
  
  console.log('In ForEach loop...');
  
  console.log('obj is ' + JSON.stringify(obj));
  
  //Directly accessing the object's properties as needed.
  console.log('obj.key is ' + obj.key);
  
});

To update your code, you can use either for...in or forEach as shown below:

var buttonsQuery = 'pages/userpage2';

var userPages = [{
    _id: "...",
    _rev: 1,
    _url: "...",
    key: "pages/auth"
  },
  {
    _id: "...",
    _rev: 13,
    _url: "...",
    key: "pages/userpage2"
  },
  {
    _id: "...",
    _rev: 13,
    _url: "...",
    key: "pages/",
    value: "/pages/userpage1"
  }
]

console.log('Iterating using for...in');
for (var prop in userPages) {

  console.log('prop is ' + prop);

  //Accessing the page object using the property name.
  var page = userPages[prop];

  console.log('page is ' + JSON.stringify(page));

  if (page.key.startsWith(buttonsQuery)) {
    console.log("Matching page found: ", page);
  }
}


//Better way to iterate if userPages is an array:
console.log('iterating using forEach');
userPages.forEach(function(page) {

  //The page object is already available within the loop.
  //No need to access the array again.
  console.log('page is ' + JSON.stringify(page));

  //Accessing the object's properties as needed.
  if (page.key.startsWith(buttonsQuery)) {
    console.log("Matching page found: ", page);
  }
});

You may also consider using a for...of loop for iteration, but keep in mind that it's not supported in Internet Explorer.

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 using a wildcard router in Node.js/Express.js, the static router may not be recognized

While using this specific route along with my other routes, I encounter an issue with serving static files: var public_dir = path.join(__dirname, 'public'); app.use('/public', express.static(public_dir)); However, when I add the follo ...

Data structure for Highcharts:

Recently, I've been experimenting with Highcharts (http://www.highcharts.com) in a test application built on rails 3.1.1 and HAML. As someone who is still new to JavaScript, I'm striving towards achieving a seamless integration of Highcharts. Wi ...

Incorrect footer navigation on my Vuepress website

I'm in the process of developing a vuepress single page application for showcasing and providing downloads of my personal game projects. When it comes to website navigation, I am aiming to utilize the native sidebar exclusively. This sidebar will hav ...

The oddity of a lone quotation mark trying to break

var x = "Test \'" > undefined var y = "Test '" > undefined x === y > true x > "Test '" https://i.stack.imgur.com/ZrHo5.jpg Aha! Both of these strings are actually equal (as shown in the example code) - but why is that the ...

Does ECMAScript differentiate between uppercase and lowercase letters?

It has come to my attention that JavaScript (the programming language that adheres to the specification) is sensitive to case. For instance, variable names: let myVar = 1 let MyVar = 2 // distinct :) I have not found any evidence in the official specific ...

Implement dynamic configuration injection by allowing users to specify the name of a configuration file during runtime, instead of having it fixed in the code

In my development using webpack, I am exploring ways to make my application configurations more dynamic. Presently, the project is a create-react-app that has been ejected. For instance, when creating a local build in my package.json file, I include the f ...

When attempting to send data using jQuery to PHP, an issue arises where PHP is unable to receive the information, resulting in an undefined variable

Has anyone successfully sent data from an HTML select to a PHP file using jQuery? I've tried multiple solutions suggested here, but none seem to be working for me. Below is the code I'm using: <select id="city" name="city" > <optgro ...

Steps for disabling and collapsing an individual header on the JQuery Accordian

Looking to adjust the behavior of 4 headers in accordions? Specifically, you want to collapse and disable only the first header out of the set. Here's how: $("#ExpandCollapse").accordion({ active: false, collapsible: true }); To ...

Froala Editor experiencing crashes during editing process

When utilizing the Froala editor in AngularJS 1.6, I encountered a problem where adding HTML in code view and attempting to edit it in view mode caused the editor to crash. Interestingly, this issue did not arise on my local system when using WampServer w ...

Choosing an ID along with a numerical value in jQuery

Being new to both stackoverflow and jQuery, I'm facing a challenge in creating a basic function. In my website, there are multiple links with IDs such as "filtro1", "filtro2", and so on. My goal is to write a single piece of code that will be trigger ...

`Developing reusable TypeScript code for both Node.js and Vue.js`

I'm struggling to figure out the solution for my current setup. Here are the details: Node.js 16.1.x Vue.js 3.x TypeScript 4.2.4 This is how my directory structure looks: Root (Node.js server) shared MySharedFile.ts ui (Vue.js code) MySharedFi ...

Is there a method by which I can access information from a linked document in Firebase?

I am relatively new to firebase and I am attempting to retrieve data from a referenced document in another collection to display. Link 1 Link 2 This is how I add a student and the parent's ID: const newStudent = { name: req.body.name, grade: ...

The Bootstrap carousel spiraled into disarray

I am facing an issue with the basic bootstrap carousel. My goal is to make the slides move every four seconds. The current setup of the carousel code is as follows: $(document).ready(function() { fixCarousel(); }); function fixCarousel() { $('.c ...

Ways to retrieve the total of all the values stored within an object created using a constructor function

Currently, I am in the process of creating an RPG character builder where each character is allocated 10 points to distribute among their characteristics and select advantages. Character Constructor function character(str, dex, con, int, wis) { this ...

Error message in my Angular project: Invalid Target Error

Out of nowhere, I encountered an invalid target error while running my Angular project with the command: npm start An unhandled exception occurred: Invalid target: {"project":"agmbs","target":"build","configur ...

Guide to swapping images based on conditions using Angular JS

I am trying to display an image based on data received from an API response instead of text. If the value is true, I want to show an access symbol. If the value is false, I want to show a deny symbol. However, when attempting this, I am only getting th ...

Having trouble running a form due to the inclusion of JavaScript within PHP code

My PHP code includes a form that connects to a database, but when I add JavaScript to the same file, the form does not execute properly. (I have omitted the insert code here.) echo '<form action="$_SERVER["REQUEST_URI"];" method="POST">'; ...

Using AngularJS location.path for unique custom URLs

Control Code: $scope.$on('$locationChangeStart', function () { var path = $location.path(); var adminPath = '/admin/' ; if(path.match(adminPath)) { $scope.adminContainer= function() { return true; }; }); HTML <div clas ...

Can you explain the concepts of 'theme' and 'classes'?

Currently, I am working on a web application using React. I have chosen to incorporate the latest version of Material-UI for designing the user interface. During this process, I came across the demo examples provided by Material-UI (like ) In each demo ...

Whenever I try to access my Node.js API from Heroku's live server, I encounter a CORS policy error

Whenever I try to access my Node.js API from the Angular app (running on a local setup) and host the API on Heroku's live server, I encounter the following error: CORS policy: No 'Access-Control-Allow-Origin'. Interestingly, when I host the ...