Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I have a JSON file containing some data I d like to access on my AngularJS website. Now what I want is to get only one object from the array. So I d like for example Item with id 1.

The data looks like this:

{ "results": [
    {
        "id": 1,
        "name": "Test"
    },
    {
        "id": 2,
        "name": "Beispiel"
    },
    {
        "id": 3,
        "name": "Sample"
    }
] }

I d like to load the data with AngularJS $http functionality like this:

$http.get("data/SampleData.json");

which is working. But how can I now get a specific data object (by id) from the array I get from $http.get ?

Thanks in advance for your help.

Greets Marc

share|improve this question
    
Have you given it a go yourself? If so, can we see what you came up with? – simonlchilds Oct 25 '13 at 12:38
1  
Well I have no idea which way would be the best using AngularJS. What I dont like is to iterate over the array and do a equals on the id. Maybe there is a better way? – marcbaur Oct 25 '13 at 12:40
    
You should rely on underscorejs or similar libraries for such processing. AngularJS is MVVM framework and may not have api for this. – Vijay Pande Oct 25 '13 at 12:46
    
@marcbaur - you have to iterate the array. Even if you use underscore, or something similar, it's functions, behind the scenes, are just iterating. – Adam Oct 25 '13 at 13:00
    
please add angular code for this – Ankush Kondhalkar Jul 15 '15 at 15:21

14 Answers 14

up vote -1 down vote accepted

The only way to do this is to iterate over the array. Obviously if you are sure that the results are ordered by id you can do a binary search

share|improve this answer
25  
... I really hope after reading this answer people don't think it's a good idea to sort an array then do a binary search. Binary search is clever, sure, but only if the array is already sorted, and in reality is: 1. easy to poorly implement, 2. Harder to read if poorly implemented. – Ben Lesh Oct 25 '13 at 14:51
1  
I would highly appreciate if the downvoters could motivate their decision. – Antonio E. Jan 13 '15 at 13:02
1  
please add angular code for this – Ankush Kondhalkar Jul 15 '15 at 15:21

i aimed to solve this problem by doing the following:

$filter('filter')(foo.results, {id: 1})[0];

A use case example:

app.controller('FooCtrl', ['$filter', function($filter) {
    var foo = { "results": [
        {
            "id": 12,
            "name": "Test"
        },
        {
            "id": 2,
            "name": "Beispiel"
        },
        {
            "id": 3,
            "name": "Sample"
        }
    ] };

    // We filter the array by id, the result is an array
    // so we select the element 0

    single_object = $filter('filter')(foo.results, function (d) {return d.id === 2;})[0];

    // If you want to see the result, just check the log
    console.log(single_object);
}]);

Plunker: http://plnkr.co/edit/5E7FYqNNqDuqFBlyDqRh?p=preview

share|improve this answer
1  
Actually, I'd think it does! After fetching the array, you can use the $filter function to filter out the item with the correct id. – flup Jun 24 '14 at 19:39
6  
This should be the accepted answer. I had the same question in my head and this answer is the only one that uses existing AngularJS and isn' reinventing the wheel. And yes, it is working. – Zoran P. Jul 3 '14 at 14:17
2  
+1 for this being the accepted answer. Best solution using angular libraries. – Aznim Oct 7 '14 at 10:08
    
A related topic I found useful for running the filter in an expression: stackoverflow.com/questions/17793751/… – Aaron Roller Jun 5 '15 at 8:22
    
Plunker with filter in an expression: plnkr.co/edit/yc0uZejGqWTcUVKvI7Tq?p=preview – Aaron Roller Jun 5 '15 at 8:28

personally i use underscore for this kind of stuff... so

a = _.find(results,function(rw){ return rw.id == 2 });

then "a" would be the row that you wanted of your array where the id was equal to 2

share|improve this answer
    
I really love underscore, but, does it worse having another JavaScript library? – genuinefafa Jul 26 '14 at 3:09
5  
Note that find can potentially return multiple objects. Since we only want one, we can use findWhere which only returns the first occurrence (which we know is the only occurrence), e.g. a = _.findWhere(results, {id: 2}). – Gregory Goltsov Sep 18 '14 at 16:47

You can use ng-repeat and pick data only if data matches what you are looking for using ng-show for example:

 <div ng-repeat="data in res.results" ng-show="data.id==1">
     {{data.name}}
 </div>    
share|improve this answer
1  
If your array has more than a trivial number of items, this will create a lot of unnecessary scopes which may slow down your application. – The DIMM Reaper Sep 2 '15 at 18:37

You can just loop over your array:

var doc = { /* your json */ };

function getById(arr, id) {
    for (var d = 0, len = arr.length; d < len; d += 1) {
        if (arr[d].id === id) {
            return arr[d];
        }
    }
}

var doc_id_2 = getById(doc.results, 2);

If you don't want to write this messy loops, you can consider using underscore.js or Lo-Dash (example in the latter):

var doc_id_2 = _.filter(doc.results, {id: 2})[0]
share|improve this answer

Unfortunately (unless I'm mistaken), I think you need to iterate over the results object.

for(var i = 0; i < results.length; i += 1){
    var result = results[i];
    if(result.id === id){
        return result;
    }
}

At least this way it will break out of the iteration as soon as it finds the correct matching id.

share|improve this answer
    
Not a good practice to use for..in over arrays. – kamituel Oct 25 '13 at 13:11
    
Why? Do you have anything to back that up? – simonlchilds Oct 25 '13 at 14:27
6  
Well, do you know what..? I just went off to re-read Javascript - the good parts to counter your argument and I am wrong! For all this time I've been doing it wrong! It hasn't caused me any problems though... yet. I've updated my answer. – simonlchilds Oct 25 '13 at 14:34

For anyone looking at this old post, this is the easiest way to do it currently. It only requires an AngularJS $filter. Its like Willemoes answer, but shorter and easier to understand.

{ "results": [
    {
        "id": 1,
        "name": "Test"
    },
    {
        "id": 2,
        "name": "Beispiel"
    },
    {
        "id": 3,
        "name": "Sample"
    }
] }

var object_by_id = $filter('filter')(foo.results, {id: 2 })[0];
// Returns { id: 2, name: "Beispiel" }
share|improve this answer

If you want the list of items like city on the basis of state id then use

var state_Id = 5;
var items = ($filter('filter')(citylist, {stateId: state_Id }));
share|improve this answer

I just want to add something to Willemoes answer. The same code written directly inside the HTML will look like this:

{{(FooController.results | filter : {id: 1})[0].name }}

Assuming that "results" is a variable of your FooController and you want to display the "name" property of the filtered item.

share|improve this answer

If you can, design your JSON data structure by making use of the array indexes as IDs. You can even "normalize" your JSON arrays as long as you've no problem making use of the array indexes as "primary key" and "foreign key", something like RDBMS. As such, in future, you can even do something like this:

function getParentById(childID) {
var parentObject = parentArray[childArray[childID].parentID];
return parentObject;
}

This is the solution "By Design". For your case, simply:

var nameToFind = results[idToQuery - 1].name;

Of course, if your ID format is something like "XX-0001" of which its array index is 0, then you can either do some string manipulation to map the ID; or else nothing can be done about that except through the iteration approach.

share|improve this answer
    projectDetailsController.controller('ProjectDetailsCtrl', function ($scope, $routeParams, $http) {
    $http.get('data/projects.json').success(function(data) {

        $scope.projects = data;
        console.log(data);

        for(var i = 0; i < data.length; i++) {
        $scope.project = data[i];
        if($scope.project.name === $routeParams.projectName) {
            console.log('project-details',$scope.project);
        return $scope.project;
        }
        }

    });
});

Not sure if it's really good, but this was helpful for me.. I needed to use $scope to make it work properly.

share|improve this answer

try this json data { "results": [ { "id": 1, "name": "Test" }, { "id": 2, "name": "Beispiel" }, { "id": 3, "name": "Sample" } ] }

Angularjs:

.controller('HomeCtrl', function($scope, $http,) {
    $http({
            url:'http://localhost/result.json',
            method  : "POST"}).success(function(data) {
            var id=data.results[0].id;
            var name=data.results[0].name;
         //if you want second item from json data 
           var name=data.results[1].name;
          ......
    });
share|improve this answer
2  
you should explain what your short answer have more than the high quality ones already existing. – Félix Gagnon-Grenier Jun 17 '15 at 19:14

If you use $resource which is made to interact with resourceful data sources.

You can also use it to read data from a json file.

Here is a simple example using get() method returns a single result You can use query() method that returns an array of objects.

get your id from the view for example :

<input type="text" ng-model="id"></input>

In Controller :

var result = $resource('data/SampleData.json/:id' , {id: $scope.id }).get();

Docs : https://docs.angularjs.org/api/ngResource/service/$resource

share|improve this answer

use $timeout and run a function to search in "results" array

app.controller("Search", function ($scope, $timeout) {
        var foo = { "results": [
          {
             "id": 12,
             "name": "Test"
          },
          {
             "id": 2,
             "name": "Beispiel"
          },
          {
             "id": 3,
            "name": "Sample"
          }
        ] };
        $timeout(function () {
            for (var i = 0; i < foo.results.length; i++) {
                if (foo.results[i].id=== 2) {
                    $scope.name = foo.results[i].name;
                }
            }
        }, 10);

    });
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.