problem with iteration in angularjs

I am a beginner in AngularJS and I am trying to create an object using data from a json file.

This is the content of my json file:

[
  {"id": 1, "name": "user1", "select": false },
  {"id": 2, "name": "user2", "select": false },
  {"id": 3, "name": "user3", "select": false },
  {"id": 4, "name": "user4", "select": false },
  {"id": 5, "name": "user5", "select": false }
]

My goal is to use a foreach loop to identify which users have select == true and add their usernames to a new array. Here is my initial attempt:

'use strict';

angular.module('apiOmat', [])


  .controller('UsersCtrl', function($scope, $http){
    $http.get('users.json').then(function(usersResponse) {
      $scope.users = usersResponse.data;
    });


$scope.submit = function(message,title){

var tempArr = [];
angular.forEach($scope.users.name, function(value,key){
 tempArr.push(value);
});

console.log(tempArr);

    $scope.messagebody = '{ "title" = "' + title + '", "message" = "' + message  + '"}'; 
}

 });

I also attempted this approach:

  $scope.submit = function(message,title){

    var tempArr = [];
    angular.forEach($scope.users, function(value,key){
     tempArr.push( { key :  value } );
    });

    console.log(tempArr);

When checking the Console, it shows 5 objects but without any values. It just displays: 1: Object 2: Object 3: Object ...

I understand that the logic for true or false evaluation is missing. However, I want to address this issue before implementing the query.

Answer №1

When tackling this issue:

I am looking to iterate through each user with a foreach-loop and identify those with the property select set to true, then add their usernames to a new array.

$scope.submit = function(message,title){
   var tempArr = [];
   angular.forEach($scope.users, function(item){
     if( item.select == true){
       tempArr.push(item);
     }
   });

An alternative approach that is more concise and efficient is to utilize filter.

$scope.submit = function(message,title){
    var tempArr = ($scope.users).filter(function(d){
         return (d.select == true);
    });
 });

console.log(tempArr)

Answer №2

give this a shot

   $scope.submit = function(message,title){
   var tempArr = [];
   angular.forEach($scope.users, function(user){
   tempArr.push( {"name":user.name} );
   });

Answer №3

Give this a shot

let tempArray = [];
angular.forEach($scope.people, function(person){
    person.isSelected && tempArray.push(person.name);
});

console.log(tempArray);

Answer №4

give this a shot

$scope.sendData = function(data,subject){

var items = [];
angular.forEach($scope.peopleList, function(item,index){

if(item.selected == true)
{
 items.push( item.fullName );
  }
});

console.log(items);

Answer №5

Embrace simplicity:

$scope.saveData = function(data, heading){
   var selectedUsers = [];
   angular.forEach($scope.users, function(user){
    if( user.isSelected == true) //filter users with isSelected:true
      selectedUsers.push( {"name_as_key":user.name} ); //name_as_key can be modified if needed
   });

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

Using CoffeeScript to pass a method into SetTimeOut

Here is my CoffeeScript snippet: setTimeout (-> @checkProgress()), 5000 After executing this code in the browser, I encountered the following error message: TypeError: this.checkProgress is not a function The actual method implementation looks like ...

The button functionality gets hindered within the Bootstrap well

I'm trying to figure out what's wrong with my code. Here is the code: https://jsfiddle.net/8rhscamn/ <div class="well"> <div class="row text-center"> <div class="col-sm-1">& ...

Tips for retrieving information from a dynamically created form using VUE?

Welcome Community I am working on a parent component that includes a child component. The child component dynamically renders a form with various controls from a JSON object retrieved via a Get request using Axios. My goal is to be able to read and loop ...

The sluggishness of the comment system is attributed to the intricate layers

A new photo viewing and commenting system has been developed, allowing users to interact with albums. When a user clicks on an album, they are directed to a page where the first photo, along with comments and replies, is displayed in the center. All other ...

Getting PHP Data from AngularJS: A Step-by-Step Guide

I have successfully sent FormData from AngularJS to PHP, but I am struggling to figure out how to get the $base64 variable back into my AngularJS code. The documentation provided by AngularJS hasn't been very helpful in this regard. https://docs.angu ...

The data being retrieved from the controller in AngularJS is not displaying as expected

Just started learning AngularJS. Currently following this MEAN Stack Intro: Build an end-to-end application Created a basic html file to test angularjs. index.html <html> <head> <meta charset="utf-8"> <title> ...

javascript troubleshooting issues with Array.prototype.filter when dealing with false values

//This function removes falsey values from an array function filterFalseyValues(arr) { return arr.filter(ele => ele); } console.log(filterFalseyValues([0, "ate", "", false, 9])); I'm confused about why just "ele" works as a condition. I am simpl ...

Navigating Parse object attributes within AngularJS

Currently, I am in the process of developing an AngularJS application that utilizes data from a parse-server backend. To retrieve this data, I use services that are called from my controllers. However, as Parse objects require all properties to be accessed ...

When is the appropriate time to provide arguments to the constructor of a TypeScript service?

I am grappling with the concept of when to pass arguments to a service's constructor versus passing them in the execution of the service. For instance, I have a service that filters rows from an Excel sheet: @Injectable() export class FilterRowsServi ...

Discovering a div within an element using an Angular TypeScript directive

I've been working with TypeScript in an Angular project. Recently, I created a directive that consists of a div containing text and a close button with the class name 'block-close'. Now, my challenge is to implement a click function for th ...

Tips for optimizing webpage loading time by registering a client script resource at the bottom of the page

Lately, I've been finding Extender controls on Asp.net quite annoying. Script controls that inject javascript at the top of the web page have me reconsidering if there is a better way to place them at the bottom, similar to using ClientScriptManager.R ...

Cached images do not trigger the OnLoad event

Is there a way to monitor the load event of my images? Here's my current approach. export const Picture: FC<PictureProps> = ({ src, imgCls, picCls, lazy, alt: initialAlt, onLoad, onClick, style }) => { const alt = useMemo(() => initial ...

Handling exceptions in the event that the backend URL resource cannot be accessed

I'm facing an issue with my Vue.js single file component where I am trying to catch exceptions when the URL requested by axios.post is unreachable. I have encapsulated the entire code in a try block, but for some reason, the alert in the catch block i ...

Showing subcategories when clicked using only JavaScript

The solution can be found below I have created a dropdown menu that currently shows the submenu on hover using the following CSS: .main-menu ul li:hover > ul { display: block; } However, my design requires the submenu to appear on click and stay visi ...

Loading templates asynchronously - Loading them for the first time

My client-side JS app requires loading a template to display each item, such as notes. The issue lies in the asynchronous aspect. The template loads every time a note calls the render function instead of just once. Below is some code snippet: var notes ...

Why aren't the divs appearing on the page?

I have developed a JavaScript and PHP page where the script in the PHP page sends data to my SQL database. However, the result is not displayed on my home page. Here is the code snippet: function getVote(question_ID) { var option_ID = document.queryS ...

The password prompt window refuses to align with the center of the screen. This

I've been struggling to position the Javascript popup notification using the width, height, top, and left parameters in the window.open function. No matter what I attempt, it stubbornly remains in the top-left corner. Can someone offer some guidance o ...

I am having trouble with searching for places using the Google API in my Node

Recently, I've been working on integrating the Google Maps API places feature into my project. Thankfully, I came across an npm module that simplifies the process of connecting it to node. Check out the npm module here! After downloading the module ...

Explaining the functionality of this code: ``.html(_.template()({ }))``

While reading through the source code of an application, I came across this particular line: $('#div1').html(_.template($('#div2').html())({Id: app.Id(id)})); I comprehend the use of $('#div1').html(), however, I am puzzled ...

Generate barcodes using Angular 2

Can anyone point me in the direction of an Angular 2 Barcode Generator capable of creating code 128 barcodes? I've been searching but haven't had any luck finding one. If you have any suggestions or can offer assistance, it would be greatly appr ...