user3438917 user3438917 - 2 months ago 7
AngularJS Question

Accessing value in sub nested object in JSON with Angular

I'm trying access values in sub array objects of results:

results: [
{
list_name: "E-Book Fiction",
display_name: "E-Book Fiction",
bestsellers_date: "2016-09-03",
published_date: "2016-09-18",
rank: 1,
rank_last_week: 0,
weeks_on_list: 1,
asterisk: 0,
dagger: 0,
amazon_product_url: "http://rads.stackoverflow.com/amzn/click/1250022134",
isbns: [],
book_details: [
{
title: "A GREAT RECKONING",
description: "An instructor at the police academy is found murdered, perhaps by one of the cadets favored by Armand Gamache, the retired homicide chief of the Sûreté du Québec.",
contributor: "by Louise Penny",
author: "Louise Penny",
contributor_note: "",
price: 0,
age_group: "",
publisher: "Minotaur",
primary_isbn13: "9781250022127",
primary_isbn10: "1250022126"
}
],
reviews: [
{
book_review_link: "",
first_chapter_link: "",
sunday_review_link: "",
article_chapter_link: ""
}
]
}


so that I can grab values like
title
from
book_details
, but currently only able to display the whole response with:

<article class="search-result row" ng-repeat="books in results">
<div class="col-xs-12 col-sm-12 col-md-3">
{{books}}
</div>
</article>


My controller is fairly simple, just grabbing the result:

myBooks.controller('bookController', function($scope, $http){
$http.get("data-url")
.success(function(response) {
console.log(response);
$scope.results = response;
});
});


A screenshot of the object in web console:

enter image description here

Answer

You can write it like this . Create a new books array in the scope by iterating over the results array.

app.controller("MyController", ["$scope","$http",
function($scope, $http) {

        $scope.books;

         $http.get('test.json').then(function (response){
              console.log(response.data.results);
             $scope.results = response.data.results;
             $scope.results.map(function(obj, index) {
               if(obj.book_details) {
                 if(!($scope.books)) {
                   $scope.books = [];
                 }
                 for(var i in obj.book_details) {
                  $scope.books.push(obj.book_details[i]);
                 }
               }
             });

             console.log($scope.books);
    });                

}]);

<article class="search-result row" ng-repeat="book in ">
    <div class="col-xs-12 col-sm-12 col-md-3">
        {{book.title}}
    </div>
</article>

Working link

Comments