2

I am working on a single page app using dynamic routing. I get my bookid from the URL as below

myApp.controller('BookCtrl', function($scope,$routeParams) {
    $scope.mybookid=$routeParams.bookurl;
});

Here is my data

var bookdata  = {
"records": [
  {
    "seriesid": "SpectrumSeries",
    "name": "White Curse",
    "bookid": "WhiteCurse",
    "image": "book1",
  }

...
]};

In the above controller, how to I filter out an object that has bookid that equals to $scope.mybookid? I know I can do this by ng-repeat and filter but is there a more efficient way?

4
  • is bookid unique in records? Commented Jun 5, 2015 at 9:14
  • so instead array you can use object and just get value by property name, like: var bookdata = { "records": { "WhiteCurse" : { "seriesid": "SpectrumSeries", "name": "White Curse", "bookid": "WhiteCurse", "image": "book1", } and then records[$scope.mybookid] Commented Jun 5, 2015 at 9:17
  • mybookid is a string, (.i.e. "WhiteCurse", not a number) because I get it from the URL, so is this approach possible? Commented Jun 5, 2015 at 9:21
  • you need change your array records to object, and then all work, in my sample - records is object, not an array Commented Jun 5, 2015 at 9:23

1 Answer 1

2

Use filter in javascript:

var filteredBooks = bookdata.records.filter(function(book){
    return book.bookid == $scope.mybookid; 
});

The filteredBooks array will contains all the book with your bookId.

Sign up to request clarification or add additional context in comments.

1 Comment

getting property from object, i think more efficient then filtering array

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.