How to access a specific element in an array hash with AngularJS using name or

Here is an example of an angular array used in a select tag:

var names= [{name: 'Superman', val: '1'}, {name: 'Batman', val: '2'}];
$scope.names =names;
$scope.FormData = {};
$scope.FormData.name = $scope.names[1];

In the above array, how can I select an item using its name or val rather than by index (1):

$scope.FormData.name = $scope.names['2']; #will select the {name: 'Batman', val: '2'}

You can find more details about this topic in a question I posted on Stack Overflow here.

Answer №1

Why not utilize the built-in $filter if you are working with angular?

For more information on using $filter, check out: https://docs.angularjs.org/api/ng/filter/filter

In your scenario, if you need to filter in the controller, the following code will return an Array containing all occurrences within names that match the search term 'Superman':

$filter('filter')($scope.names, {name:'Superman'})

If you are sure that there will be at least one match, you can retrieve the first match by doing this:

var matches = $filter('filter')($scope.names, {name:'Superman'});
var match = matches[0]:

Keep in mind that if there are no matches, then match will be undefined

Answer №2

To create a reusable function, you can implement it in the following way:

$scope.searchItem = function(list, key, value){
    var result = {};
    angular.forEach(list,function(item){
        if(item[key]){
            if(item[key] === value){
                result = item;
            }
        }
    });
    return result;
};

$scope.FormData.title = $scope.searchItem(titles,'title','Superman');

Answer №3

If I want to select an item by name in the given array rather than by index (1), how can I achieve this?

To accomplish this, you can utilize the find method from the Lodash library (http://lodash.com/docs#find):

var names= [{name: 'Superman', val: '1'}, {name: 'Batman', val: '2'}];

var matchingBatman = _.find(names, { name: 'Batman' });

The value of matchingBatman will be: {name: 'Batman', val: '2'}

A similar approach can be used to find by val:

var matchingBatman = _.find(names, { val: '2' });

Answer №4

When seeking an alternative to utilizing a pre-existing library, you can opt to create your own function

function findObjectByProperty(key, value){

    for(var index=0; index< $scope.names.length; index++){
        if($scope.names[index][key] === value){
           return $scope.names[index];
         }
     }

}
$scope.FormData.name  = findObjectByProperty('value','2');

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 a text box in jQuery to perform basic calculations is a straightforward process

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Creating a Lens Calculator Web App</title> <link href="http://code.jquery.com/mobile/1.0a3/jque ...

I'm trying to figure out how to retrieve data from a JQuery autocomplete response that contains an array. Specifically, I want

https://i.stack.imgur.com/YpuJl.pngThis form field is for entering text input. <span> <img src="images/author2.jpg" width="50" /> //The profile picture displayed here is static but in the database I have a dynamic image. <input class="sea ...

The curious behavior of $viewContentLoaded in Angular

For my jQuery code, I wanted it to run immediately after the template view was loaded and the DOM was modified. To achieve this, I initially used the $viewContentLoaded event in my controller. $scope.$on('$viewContentLoaded', function(){ // ...

Creating and experimenting with AngularJS applications (and applications overall)

I am currently working on developing an app, following the trend of using a REST API for the back-end and Angular (previously Backbone and jQuery) for the front-end. Initially, stubbing the REST API for testing purposes is straightforward; however, as deve ...

Prevent selection of rows in the initial column of DataTables

I am working on a basic datable, the code can be found here JS: var dataSet = [ ["data/rennes/", "Rennes", "rennes.map"], ["data/nantes/", "Nantes", "nantes.map"], ["data/tours/", "Tours", "tours.map"], ["data/bordeaux/", "Bordeaux", ...

How can I uniquely combine a code with an existing CSS class and make modifications to it?

I am using ngx-skeleton-loader and I would like to change the color, but I am facing some difficulties. Here is an image that illustrates the issue. When looking at the developer tools, you can see the styles action in the styles action bar. .loader ...

Clicking again on the second onclick attribute

I have an image file named image1.png. When the button is clicked for the first time, I want it to change to image2.png. Then, when the button is clicked for a second time, I want it to change to yet another image, image3.png. So far, I've successful ...

Printing only the last element of a Swift array

This is my class. class dictionaryWord Object { @objc dynamic var word: String? @objc dynamic var Defination: String? @objc dynamic var dateCreated: Date? } The goal is to split the Definition by commas to display each part on a new line. W ...

Is it possible to create a MongoDB query that can retrieve a specific number of documents from different types within a single collection?

If I have a collection named "pets" with three different types of animals: cat, dog, and bird What if there are 10 cats, 10 dogs, and 10 birds in the collection (30 documents total)? Can I create a query that retrieves 3 cats, 2 dogs, and 1 bird all at o ...

"Please advise on the proper method for deleting a floating-point 2D array in C++ while

Hey there, currently I'm using QT for my project and facing issues with deleting a 2D float array from memory. My work involves images and it is crucial to delete arrays to prevent excessive memory consumption. I attempted the following method but ...

Messages displayed in the console for Angular version 1.2.x

Have you noticed the strange appearance of error messages in Angular 1.2.16 (and even in version 1.3 beta)? Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.16/$injector/ modulerr?p0=myapp&p1=Error%3A%…g%2F1.2.16 %2F%24injector%2 ...

Employing jQuery to redirect to a different URL when a button is clicked

I've been experimenting with a project that involves both JQuery and AJAX. One of the features I have added is JQuery autofill. Here is the code snippet for the form: <form class="form-horizontal"> <div class="form-group"> < ...

When initializing React Native, the Android, iOS, and app folders seem to be missing

https://i.sstatic.net/bkmvE.png Where have my android, ios, and app folders gone? Also, why are the index js files missing? I am currently working with React Native version 0.1.10 on a Windows 7 operating system. ...

MariaDB not properly handling empty lists in JSON_ARRAY function

Encountering an issue in my MariaDB (version 10.3.18) when utilizing the JSON_ARRAY function. When my subqueries do not return any results, instead of an empty array, I receive an array containing 1 null result. Example: SELECT JSON_ARRAY() // -> [] d ...

Merging two distinct arrays of objects in JavaScript can be achieved by utilizing various methods and

I have a challenge where I need to merge two arrays of objects in a nested way. var array1=[{ PersonalID: '11', qusetionNumber: '1', value: 'Something' }, { PersonalID: '12', qusetionNumber: '2& ...

"Incorporate keyframes to create a mouseleave event with a distinctive reverse fade

After posing a similar question a few days back, I find myself encountering yet another hurdle in my project. The task at hand is to switch the background image when hovering over a button with a fade-in effect using @keyframes. However, I'm stuck bec ...

Send information from a Chrome extension to a .NET application

My goal is to transmit data from my chrome extension to my .net application using AJAX. I am utilizing a background script to send the data, but unfortunately I am not receiving the data on my server. I suspect there may be an issue with configuring the ...

Save the promise object from the $http GET request in a local storage

Struggling to wrap my head around how to update data on a graph without the proper Angular service knowledge. All I want is to retrieve a JSON object with one GET request and save it locally on my controller. This way, I can use the original JSON to displa ...

I'm having trouble getting jQuery UI's droppable to function properly. How can I troub

Recently, I created a drag and drop game to enhance my jQuery UI skills. However, I am facing an issue where the circle cannot be dropped on the square with the same color. Also, when it does work, the circle ends up behind the square instead of on top. It ...

Insert two backslashes before a single backslash in PHP

I have been looking for a solution everywhere and have experimented with the JavaScript replace() function, str_replace, addslashes, and stripslashes, but I still can't seem to get the desired output. Here is what I am attempting: str_replace("&bsol ...