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.