Look through an array to find a particular string and send the result back to an AngularJS view

Currently, I am faced with the task of searching through a JSON output in my code to locate a specific string (for instance 'name_col_lbl') and then extracting its corresponding value ('Name' in this example) for AngularJS to display in the view.

$scope.globalContent = [
    {"id":"1","module":"student_reg","item":"name_col_lbl","value":"Name"},
    {"id":"2","module":"student_reg","item":"bday_col_lbl","value":"Birthdate"}
]
angular.forEach($scope.globalContent, function(el){
    $scope.nameLbl = el ***Here is where I'm struggling to extract the desired value***;
    $scope.bdayLbl= el ***This is another spot where I need to retrieve the expected value***;

});

Despite my efforts, I have not yet found an efficient solution for this dilemma. Your assistance is greatly appreciated!

Answer №1

Here's a solution you can try:

var $scopeglobalContent = [
    {"id":"1","module":"student_reg","item":"name_col_lbl","value":"Name"},
    {"id":"2","module":"student_reg","item":"bday_col_lbl","value":"Birthdate"}
];

for(var i = 0; i < $scopeglobalContent.length; i++){
for(key in $scopeglobalContent[i]){
  if($scopeglobalContent[i][key] == "name_col_lbl"){
    return console.log($scopeglobalContent[i].value);
    }
  }
}

This is fundamental knowledge. I recommend studying up on objects and loops to grasp how it operates and how to apply it effectively.

Answer №2

Referencing a helpful Stack Overflow response, here is a method for searching through an array of objects:

var obj = array.filter(function ( obj ) {
    return obj.item === "name_col_lbl";
});

The variable obj will contain either the value associated with name_col_lbl or undefined if the key does not exist.

Your code implementation would resemble this:

function findObject(array, keyName) {
    var obj = array.filter(function ( obj ) {
        return obj.item === keyName;
    })[0];
    return obj;
}

$scope.globalContent = [
    {"id":"1","module":"student_reg","item":"name_col_lbl","value":"Name"},
    {"id":"2","module":"student_reg","item":"bday_col_lbl","value":"Birthdate"}
]
angular.forEach($scope.globalContent, function(el){
    $scope.nameLbl = findObject($scope.globalContent, "name_col_lbl")['value]' ***This is where I need to search for the string and return its value***;
    $scope.bdayLbl= findObject($scope.globalContent, "bday_col_lbl")['value]' ***This is where I need to search for the string and return its value***;
});

The findObject function sifts through the array by identifying the first object where obj.item matches the provided keyName. This matches the obj object that is then returned. In order to display only the desired value from the object rather than the entire object itself, the result of

findObject($scope.globalContent, "name_col_lbl")
has been appended with ['value'], which extracts the value corresponding to the value key to be shown in the Angular view.

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

Assigning a Value to ngTypeahead in Reactive Model-Driven Form

Currently, I am implementing an Angular Reactive form which includes a typeahead field using ng-bootstrap typeahead. Within this setup, I have generated a list of states through an interface structured as follows - export interface IContactStates { Id: ...

Chrome not triggering the fullscreenchange event

I've been attempting to track when the browser goes into fullscreen mode. Everywhere I look, this blog is mentioned as the go-to resource on the fullscreen API. According to this SO answer, it should work. Fullscreen API: Which events are fired? B ...

Integrate React tags with Redux form to ensure the values are transmitted as an array within the payload

I am currently working on a redux-form that contains a component for tags. I am struggling to figure out how to retrieve the tag values in an array as a payload. Any help would be greatly appreciated. Below is the code snippet for the tags component: ...

How to activate select only when specific options are chosen using jQuery

I am working on a form that has 1 select element disabled, with 4 options. I am looking to implement a jQuery function that will perform the following actions: If OPTION #1 is clicked, it should check if any other options are selected and reset them (eras ...

Progress bar for AJAX file loading for Flash player

Looking to create a progress bar using AJAX for a flash file. Check out this demo here: I tried to analyze their page, but the JavaScript is encrypted and I'm not very skilled in JS. Any suggestions? Thank you! ...

If a user enters an incorrect path, the goal is to automatically redirect them to the homepage while displaying the correct URL in AngularJS

When the URL is manually edited, the webpage displays the same content with a different URL structure. For instance, http://www.example.com/# and http://www.example.com/#/abc both show identical content. I would like to implement a redirect for any edite ...

Angular1 Custom Filter is not triggering as expected

I am facing an issue with two integer fields in a digest: genres and secondary_genre. For the genres field, I have a dropdown that returns a value of (ng-model = query.genres). I attempted to create a custom function that compares the genre and secondary ...

Maximizing Efficiency: Implementing Loading Panels in AngularJS

I need a loading icon (spinner) to appear when I press the button and the request is sent from the controller to the server. It may take some time for a response, so I want the loading icon to be displayed during this process. Once the server responds to t ...

I encountered an issue with loading an array from session storage in Java Script

I am struggling to restore and reuse a created array in HTML. I attempted using JSON, but it was not successful for me. In the code below, I am attempting to reload items that were previously stored in an array on another page. However, when I try to loa ...

Increasing the top padding of a resized iframe thanks to iframe-resizer

Currently, I am utilizing the remarkable iframe-resizer library to resize an iFrame while keeping it in focus. The challenge I am facing is my inability to figure out how to include additional padding at the top of the iFrame once it's resized. The ...

Tips for creating a scrollable smiley input field

I have a chat system where I am incorporating smileys from a predefined list. QUERY I am looking to create a scrolling feature for the smileys similar to how it is implemented on this particular website. The twist I want to add is to have this functiona ...

Avoid Conversion of HTML Entities in Table Cells

<table> <tr> <td>&gt;</td> </tr> <tr> <td>&&#xfeff;GT</td> </tr> </table> In the code snippet above, I have table cells containing HTML entities. A re ...

Tips for customizing the default configuration files in reactJs bootstrapping using npm

I've generated a simple greeting world ReactJS application by using the create-react-app command from npm. The directory structure provided by the application template is as follows: https://i.sstatic.net/y3K5n.png The contents of my package.json fi ...

Is there a way to target a button within an anchor tag without relying on a specific id attribute?

On my webpage, I have buttons that are generated dynamically using PHP from a MySQL table. Each button is wrapped in an anchor tag and when clicked, it triggers a Javascript function to carry out multiple tasks. One of these tasks requires extracting the ...

Finding the difference between two NSDate instances

Similar Question: How to Calculate Time Difference in iPhone My app retrieves date and time information from a JSON feed. I'm trying to figure out how to calculate the difference between the date received from the feed and the current date and ti ...

The AFNetworking AFHTTPClient does not support JSON operations with AFJSONRequestOperation

After watching this video tutorial at I have implemented my singleton AFHTTPClient code like below: + (MyClient *)sharedInstance { static dispatch_once_t once; static MyClient *myClient; dispatch_once(&once, ^ { myClient = [[MyClient allo ...

Condensing text saved in session storage

Is there a way to compress a large string stored in session storage before sending it to a server? The string can be quite sizable, sometimes reaching upwards of 2mb. Are there any compression algorithms that can help reduce the size? ...

SignalR fails to trigger client callback function

Currently, I am diving into the world of SignalR and attempting to create a basic message notification system. However, despite my limited understanding of SignalR, I am unable to display the messages after submission. I have researched multiple blogs on ...

jQuery AJAX issues on Safari and iOS gadgets

I'm facing a compatibility issue specifically with Safari and all iOS devices. I've developed this jQuery code for a project, but it seems to have trouble working with Safari. Interestingly, it works perfectly fine with Chrome, Firefox, and even ...

Filter an array using regular expressions in JavaScript

Currently, I am facing a challenge in creating a new array of strings by filtering another array for a specific pattern. For example: let originalString = "4162416245/OG74656489/OG465477378/NW4124124124/NW41246654" I believe this pattern can be ...