Picking a specific field from an array depending on a filtered value

Hello everyone, I am a newcomer to Angular and the entire MEAN stack ecosystem.

Currently, I have a MongoDB database collection structured like this:

db.users({ 
    username: "Test1", 
    fname: "Bob", 
    lname: "Saget", 
    email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="196d7c6a6d596d7c6a6d377a7674">[email protected]</a>", 
    password: "12345",  
    status: [{ 
        active: false, 
        "non-active": false, 
        suspended: true, 
        "un-confirmed": false, 
        banned: false 
    }] 
})

So far, I have been able to successfully display all users on the screen using the following code snippet:

        <tr ng-repeat="user in users">
            <td>{{user.username}}</td>
            <td>{{user.fname + ' ' + user.lname}}</td>
            <td>{{user.email}}</td>
            <td>{{user.password}}</td>
            <td></td>
        </tr>

However, my challenge arises when attempting to display the name of the field (e.g., 'suspended') from the status array based on its boolean value instead of displaying 'true'. Moreover, I only want to retrieve the records with true values (there will be only one in this case).

I have tried utilizing combinations of ng-if along with ng-repeat and filter:{} options without much success.

If necessary, I can provide additional details. How would you approach solving this issue?

Thank you very much in advance for any insights or guidance you can offer!

Answer №1

Once you have obtained the list of users, you can iterate through them and update their status as shown below.

angular.forEach($scope.users, function(a, b){
  var user = a;
  var status = a.status[0]; // <-- since status is an array, we select the first one.
  for (var k in status) {
    if (status.hasOwnProperty(k)) {
      if (status[k]) { // <-- if status is true, retrieve the key.
        user.status = k; // <-- set the user's status object to the key.
      }
    }
  }
});

You have the freedom to change user.status = k to any desired value; setting it to status will overwrite the existing status array.

Check out this working example -> http://jsbin.com/zarulo/1/edit?html,js,output

I hope this explanation helps!

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

Angular HttpClient not recognizing hashtag

I'm trying to make a REST API call, but running into issues with the developerId parameter being sent incorrectly: let developerId = "123#212"; let url = \`\${Constants.BASE_URL}\${marketId}/developers/\${developerId}\`; retur ...

Combining translate() and scale() transformations in HTML5 Canvas

I am really curious about how Canvas transformations actually work. Let's say I have a canvas with a circle drawn inside, and I want to scale the circle without moving its center point. My initial thought is: translate(-circle.x, -circle.y); scale(fa ...

Try to locate a particular sequence of characters

I am currently on a quest to locate a specific row within the database that corresponds to the message provided by the user, specifically: catalystname. After successfully indexing the given string as text within the schema: const { Schema } = mongoose; ...

Establishing the highest allowable value limit in cleave

I've integrated cleave.js into my Vue.js project to create a date input field. Here's the option configuration I used: <cleave :options="{ date: true, datePattern: ['m', 'd','Y'] ...

"Identifying the exact number of keys in a JSON object using

Is there a key in the JSON data that may or may not exist? How can I determine the total number of occurrences of this key using jQuery? JSON : jasonData = [{"test":"sa3"},{"test":"4s"},{"acf":"1s"},{"test":"6s"}]; I need assistance with implementing th ...

Challenges arise when integrating ng-model with Angular Chosen

I'm working with a table that lists users, each row ending with a button that triggers a popup form. Inside the popup, I'm using a multiple select feature with Angular Chosen to display each user's 'interests'. However, despite fet ...

I am curious if there is a wysiwyg web editor extension specifically designed for VS2010 available?

In my experience, I have been working with C#, HTML coding using VS2010 and MVC. Utilizing VS2010 has proven to be an invaluable tool for me in this process. Currently, I find myself needing to create some straightforward static web pages. I am wondering ...

Ensure one div scrolls independently while the other remains fixed using Bootstrap

I am currently in the process of constructing a web page with Bootstrap 4. The layout consists of two columns, each contained within individual divs. My requirement is for the content on the right side to be scrollable while the content on the left remains ...

Using the `Array.find()` method in an attempt to dynamically retrieve a specific object value and then return it based on the object name, but unfortunately the function is

I have a collection of objects, each containing its own nested array of objects. My goal is to utilize the Array.find() method to target individual nodes within the array and extract a value from their subarray based on name. Despite having written my fu ...

Upon installation, the extension that replaces the new tab fails to detect the index.html file

edit: Check out the Chrome Extension here Edit 2: It seems that the recent update containing the index.html file was not published due to Google putting it under revision. Apologies for forgetting to include the index.html file in the upload zip, as I ...

Unleash the power of jQuery to leverage two different input methods

Here is the code I'm working with: $('input[type="text"]').each(function(indx){ Right now, this code targets input elements with type "text". But how can I modify it to target both inputs with type "text" and "password"? Any suggestions o ...

Tips for solving the problem of page navigation using jquery-mobile

I have a jquery-mobile application with two actual HTML pages, but many more data-role="page" divs. The issue arises when transitioning from the first actual HTML page to the next one as the navigation stops working. I am not using any custom JavaScript, j ...

Connect-Domain fails to detect errors in the scenario described below:

I have chosen to implement the connect-domain module (https://github.com/baryshev/connect-domain) in order to streamline error handling within my Express application. Although it generally functions as expected, there is a peculiar issue that arises when ...

How to convert a nested array of objects into a string using JavaScript for passing as a URL parameter

So, I'm dealing with a nested JSON array of objects here. My goal is to pass it as a parameter in the URL and then save it to my MongoDB database. However, when I tried doing that, it ended up being saved as [object object]. Does anyone know how to so ...

Establishing header cache control within the KOA framework

I'm currently working on an app that is using the KOA framework, and I am struggling to understand why a specific page is being cached. Even after attempting a hard reload in all browsers, the changes do not appear unless the cache is cleared. I woul ...

"Using conditional statements to check for specific value ranges and properly handling cases where the result is undefined

Currently, I am working on a function that prompts the user to input a number and then displays a calculated score after they click a button. The score is based on the value entered by the user. While constructing this feature, I have pondered whether IF ...

What is the best way to handle an array of string inputs in Apollo Server using GQL?

My current typeDefs file contains a custom Books type structured like this: type: Books { bookId: String authors: [String] description: String title: String } For storing data, I am utilizing MongoDB with the following model schema: const book ...

Error: Unexpected character encountered

When attempting to parse an array of objects enclosed in double quotes, I encountered an error: Uncaught SyntaxError: Unexpected token ' var test = "[{'key' :'D', 'value': 'Deceased Date'},{'key' ...

Issue: Connection timeout encountered while using NPM in a Meteor project

I have been attempting to utilize the NPM package found at this link within Meteor 1.3.2.4. This package utilizes eventemitter in its functions and includes asynchronous callbacks. In an effort to make it appear synchronous, I tried using Meteor.bindEnviro ...

Loop through each row in the Datatable and access the details or child

I need to iterate through each child row in a datatable. For example, if I have AJAX data structured like this: "data": [ { "date" : "1/17/2016", "supplier" : "supplier1", "total" : "$10", "payment" : "Cash", "product" : Array[2] ...