[javascript] Get specific object by id from array of objects in AngularJS

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

This question is related to javascript arrays angularjs json object

The answer is


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);

    });

I would iterate over the results array using an angularjs filter like this:

var foundResultObject = getObjectFromResultsList(results, 1);

function getObjectFromResultsList(results, resultIdToRetrieve) {
        return $filter('filter')(results, { id: resultIdToRetrieve }, true)[0];
    }

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" }

WARNING

As @mpgn says, this doesn't work properly. This will catch more results. Example: when you search 3 this will catch 23 too


    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.


The simple way to get (one) element from array by id:

The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

function isBigEnough(element) {
    return element >= 15;
}

var integers = [12, 5, 8, 130, 160, 44];
integers.find(isBigEnough); // 130  only one element - first

you don't need to use filter() and catch first element xx.filter()[0] like in comments above

The same for objects in array

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

var secondElement = foo.results.find(function(item){
    return item.id == 2;
});

var json = JSON.stringify(secondElement);
console.log(json);

Of course if you have multiple id then use filter() method to get all objects. Cheers

_x000D_
_x000D_
function isBigEnough(element) {_x000D_
    return element >= 15;_x000D_
}_x000D_
_x000D_
var integers = [12, 5, 8, 130, 160, 44];_x000D_
integers.find(isBigEnough); // 130  only one element - first
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
var foo = {_x000D_
"results" : [{_x000D_
    "id" : 1,_x000D_
    "name" : "Test"_x000D_
}, {_x000D_
    "id" : 2,_x000D_
    "name" : "Beispiel"_x000D_
}, {_x000D_
    "id" : 3,_x000D_
    "name" : "Sample"_x000D_
}_x000D_
]};_x000D_
_x000D_
var secondElement = foo.results.find(function(item){_x000D_
    return item.id == 2;_x000D_
});_x000D_
_x000D_
var json = JSON.stringify(secondElement);_x000D_
console.log(json);
_x000D_
_x000D_
_x000D_


I know I am too late to answer but it's always better to show up rather than not showing up at all :). ES6 way to get it:

$http.get("data/SampleData.json").then(response => {
let id = 'xyz';
let item = response.data.results.find(result => result.id === id);
console.log(item); //your desired item
});

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


Using ES6 solution

For those still reading this answer, if you are using ES6 the find method was added in arrays. So assuming the same collection, the solution'd be:

const foo = { "results": [
    {
        "id": 12,
        "name": "Test"
    },
    {
        "id": 2,
        "name": "Beispiel"
    },
    {
        "id": 3,
        "name": "Sample"
    }
] };
foo.results.find(item => item.id === 2)

I'd totally go for this solution now, as is less tied to angular or any other framework. Pure Javascript.

Angular solution (old solution)

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


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.


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]

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 }));

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>    

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.


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.


Why complicate the situation? this is simple write some function like this:

function findBySpecField(data, reqField, value, resField) {
    var container = data;
    for (var i = 0; i < container.length; i++) {
        if (container[i][reqField] == value) {
            return(container[i][resField]);
        }
    }
    return '';
}

Use Case:

var data=[{
            "id": 502100,
            "name": "B?rd? filiali"
        },
        {
            "id": 502122
            "name": "10 sayli filiali"
        },
        {
            "id": 503176
            "name": "5 sayli filiali"
        }]

console.log('Result is  '+findBySpecField(data,'id','502100','name'));

output:

Result is B?rd? filiali

$scope.olkes = [{'id':11, 'name':'---Z?hm?t olmasa seçim edin---'},
                {'id':15, 'name':'Türky?'},
                {'id':45, 'name':'Az?rbaycan'},
                {'id':60, 'name':'Rusya'},
                {'id':64, 'name':'Gürcüstan'},
                {'id':65, 'name':'Qazaxistan'}];

<span>{{(olkes | filter: {id:45})[0].name}}</span>

output: Az?rbaycan


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor