Search code examples
jsonangularjsfilenames

Getting only images from JSON response using AngularJS


I have a REST call which gives the all attachments related to a Id which I pass to that call.

The JSON response should be like this

[
{
"id": 1,
"filename": "test.txt",
"size": 594,
"description": "comment",
"createdAt": "2014-04-07 12:53:24",
"binaryId": 1
},
{
"id": 2,
"filename": "dummy.png",
"size": 496,
"description": "comment",
"createdAt": "2014-04-07 12:53:34",
"binaryId": 2
},
{
"id": 3,
"filename": "else.pdf",
"size": 496,
"description": "comment",
"createdAt": "2014-04-07 12:53:34",
"binaryId": 3
},
{
"id": 4,
"filename": "some.jpg",
"size": 496,
"description": "comment",
"createdAt": "2014-04-07 12:53:34",
"binaryId": 4
}
]

Like this I will get all the files with all extensions.

So what I need here is to get only the images (.jpg, .png) from that json response ignoring other files like pdfs, text files etc.

How can I do this usimg AngularJS? Any ideas?

Thank you


Solution

  • $scope.sampleImageArray = [];
        $scope.imageArray = [
            {
                "id": 1,
                "filename": "test.txt",
                "size": 594,
                "description": "comment",
                "createdAt": "2014-04-07 12:53:24",
                "binaryId": 1
            },
     {
    "id": 2,
    "filename": "dummy.png",
    "size": 496,
    "description": "comment",
    "createdAt": "2014-04-07 12:53:34",
    "binaryId": 2
    },
     {
    "id": 3,
    "filename": "else.pdf",
    "size": 496,
    "description": "comment",
    "createdAt": "2014-04-07 12:53:34",
    "binaryId": 3
    },
    {
    "id": 4,
    "filename": "some.jpg",
    "size": 496,
    "description": "comment",
    "createdAt": "2014-04-07 12:53:34",
    "binaryId": 4
     }
        ];
    
       angular.forEach($scope.imageArray, function (data) {
                var extension = data.filename.substr((data.filename.lastIndexOf('.') + 1));
                if(extension=="png" || extension=="jpg" || extension=="jpeg")
                    $scope.sampleImageArray.push(data);
            });