Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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
 
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
add comment

5 Answers

up vote 2 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
1  
... 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. –  blesh Oct 25 '13 at 14:51
add comment

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
 
Thanks for your help. I think that will do the trick. –  marcbaur Oct 25 '13 at 13:26
add comment

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
 
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
 
Glad I helped :) –  kamituel Oct 25 '13 at 14:39
1  
This is why I love SO. Everyday is a learning day. –  simonlchilds Oct 25 '13 at 14:41
add comment

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
add comment

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
add comment

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.