1

I am using AngularJS. I have a json object as below;

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

I want to have a function such that when a matching name is found, some action is taken (in this -case, return the corresponding id.) In other words, if the input matching name is 'Tom', I want to return the id '111' based on the json object above.

I wrote some code to find a matching name.

$scope.getIdFromName = function()
        {
            angular.forEach(info, function(value, key)
            {
                //$scope.searchByName contains the name to be matched
                if (key === 'name' && value === $scope.searchByName)
                {
                    //$scope.searchById is the id to be returned
                    $scope.searchById = key;
                    alert("found");
                }
            }); 
        };

Where did the code go wrong? Or is it so wrong that it is better to be completely rewritten? Any suggestions (does not need to be angularjs) will be most welcome. Thank you very much.

1
  • This not really an angularJS issue, you're really just wanting to manipulate a collection. Using a library like UnderScore or LoDash would help you greatly as both have easy to use methods to find exactly the value you're looking for. Commented May 22, 2014 at 11:41

1 Answer 1

3

Since info is an array of objects, the key is going to be the index of each item, and value will be the whole object at that index. Your forEach should look like this:

angular.forEach(info, function(value, key)
{
    //$scope.searchByName contains the name to be matched
    if (value.name === $scope.searchByName)
    {
        //$scope.searchById is the id to be returned
        $scope.searchById = value.id;
        alert("found");
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.