Retrieving a matching value in a JSON object using AngularJS

Utilizing AngularJS, I have a JSON object presented below;

info = [
{
    "name": "Tom",
    "id": "111"
},
{
    "name": "Sam",
    "id": "222"
},
{
    "name": "James",
    "id": "333"
}
]

I aim to create a function that triggers a specific action whenever a matching name is detected (in this case, returning the corresponding id.) For instance, if the input name matches 'Tom', the desired outcome is to retrieve the id '111' from the provided JSON object.

An attempt has been made to write code for locating a matching name.

$scope.getIdFromName = function()
        {
            angular.forEach(info, function(value, key)
            {
                //$scope.searchByName holds the name to be compared
                if (key === 'name' && value === $scope.searchByName)
                {
                    //$scope.searchById captures the required id
                    $scope.searchById = key;
                    alert("found");
                }
            }); 
        };

What may have caused the malfunction in the code? Is it flawed to the extent of needing complete revision? Any suggestions (not necessarily limited to AngularJS) would be appreciated. Thank you kindly.

Answer №1

When dealing with an array of objects like 'info', the key corresponds to the index of each object, while the value represents the entire object at that specific index. To properly loop through this array using forEach, your code should resemble the following:

angular.forEach(info, function(value, key)
{
    //$scope.searchByName holds the name we are looking for
    if (value.name === $scope.searchByName)
    {
        //$scope.searchById stores the id that needs to be retrieved
        $scope.searchById = value.id;
        alert("Item found");
    }
});

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

Retrieve the key values from an object of a generic type

Is there a way to retrieve the keys of the object when it is of type T? I attempted to accomplish this using different methods such as: function getGenericTypeKeys<T>(): string[] { return Object.keys({} as T); } and function getGenericTypeKeys< ...

What is the best way to define a dynamic model name in AngularJS?

I am looking to dynamically populate a form with custom questions (check out the example here): <div ng-app ng-controller="QuestionController"> <ul ng-repeat="q in Questions"> <li> <div>{{q.Text}}</div> ...

The Angular code appears to be unable to locate the controller and items

I am a beginner in Angular and trying to develop an MVC project using Angular. I created an about.js file with the following code: (function () { var app = angular.module('myApp', []); app.controller('TecknologiesController', ...

Separate the string by commas, excluding any commas that are within quotation marks - javascript

While similar questions have been asked in this forum before, my specific requirement differs slightly. Apologies if this causes any confusion. The string I am working with is as follows - myString = " "123","ABC", "ABC,DEF", "GHI" " My goal is to spli ...

Attempting to verify the existence of a value in an SQL table prior to insertion

I have a simple table that contains an ID column and a location name column. Additionally, I have created an HTML form where users can input a new location into the table. Before adding the new location, I want to check if that location already exists in m ...

Tips for efficiently printing invoices on specific paper: Print a maximum of 20 items per sheet, and if it exceeds this limit, continue onto the next page. Ensure the total amount is

$(document).ready(function(){ var j = 23; for (var i = 0; i < j+11; i++) { if (i != 0 && i % 11 == 0) { $("#printSection div").append("<?php echo '<tr><td>fff</td></tr>'; ?>"); ...

choosing a section within a table cell

This seems like a simple task, but I'm encountering some difficulties $("#info-table tbody tr").each(function(){ $(this).find(".label").addClass("black"); }); .black{ font-weight:bold; } <script src="https://ajax.googleapis.com/ajax/libs/j ...

Issues with loading Angular 9 application on Internet Explorer 11

Having trouble with my app not loading in IE 11 after adding ngx-treeview. Encountering the error (SCRIPT1002: Syntax error), Script Error Error point in vendor.js Unsure how to resolve this issue. Works fine in chrome and firefox, but in IE11 all I se ...

Having trouble getting the jQuery keydown trigger to function properly?

After the document has finished loading, I execute this script: $(function () { $("input").keydown(); }); This script is part of a chrome extension that runs on every page the user visits. However, it does not work on certain websites like Twitter ...

Determining which index in a multi-dimensional array in Ajax JSON contains specific values

In my project, I am using PHP to return a JSON multi-array via JQuery Ajax. My goal is to identify which array contains a specific value so that I can access the values within that array. This process needs to be repeated for up to three arrays that are be ...

What is the most effective method for transferring resolved promise values to a subsequent "then" chain?

Currently, I am grappling with understanding promises by utilizing the Q module in node.js. However, I have encountered a minor setback. Consider this scenario: ModelA.create(/* params */) .then(function(modelA){ return ModelB.create(/* params */); } ...

Please provide an explanation of how babel and node.js are interconnected within the ReactJS framework

As a beginner in ReactJS, I'm curious about the role of Node.js in the React ecosystem. Can someone please explain its importance to me? ...

AngularJS Datepicker with parentheses in the Controller.js

I recently started working with angularJS in Brackets and I am attempting to implement a datepicker from https://codepen.io/anon/pen/ZvVxqg However, when I paste the JS file into my controller.js in Brackets, an error occurs. Below are the code snippets ...

How can we best store the component's state in the URL in AngularJS?

I am working with a reusable widget that has its own state. This state includes the content of the search bar (2), one or more select boxes (1), and the tree where the user can pick the currently active element (3). My goal is to create a locationManager ...

Struggling to navigate the menu on Ionic View?

Hey there! So, I'm pretty new to Ionic and I'm currently working on my first app using it as a proof of concept for my company. I've been using Ionic View on my iPhone to see how it looks on a mobile device. However, I've hit a bit of ...

Error Encountered: Unable to locate package.json file upon running npm audit fix

Trying to install sass but keep encountering an issue that I don't understand. The error message appears like the one shown in the image https://i.sstatic.net/1sy3F.png I know I should execute the command npm audit fix, but every time I try, it gives ...

Iterating over an array within an if statement to validate if all elements meet the criteria

In my code, I have a variable named 'fieldCount' and it is currently set to 5 which represents the number of fields that I have. How can I refactor the following code without explicitly mentioning each index: if ( fields[0].checkValidity() &a ...

Can you provide a list of factors that influence coverage? Additionally, is there a specific algorithm available for calculating

As part of my Angular project, I am currently focusing on writing unit test cases using the Jasmine Framework and Karma. To ensure thorough testing coverage, I am utilizing Coverage-html (Istanbul). When it comes to coverage, there are several important t ...

nodejs promises and their implementation in loops

Currently delving into the realm of promises in nodejs, here's an example code snippet for you to peruse: The result when running the below code is as follows: test - 1 test - 2 test - 3 test - 4 var Q = require('q'); var promise = Q.when( ...

Guide to presenting XML information from a web address using XSLT

I am currently working with dynamic XML sports data from a URL in a Yahoo API, and I want to display and sort a selection of this data on my website using XSLT. This is my first time dealing with XML and XSLT, and while testing, I have managed to correctly ...