jashkenas / underscore

JavaScript's utility _ belt
https://underscorejs.org
MIT License
27.33k stars 5.53k forks source link

where() function issue with searching json objects #2813

Closed ridhwaans closed 5 years ago

ridhwaans commented 5 years ago

I have a json collection stored as {"books": [{...}, ... ]} in a file. "books" is a list of json objects where each is a book. For example:

{
 "books": [
  {
   "items": [
    {
     "id": "jD8iswEACAAJ",
     "volumeInfo": {
      "industryIdentifiers": [
       {
        "type": "ISBN_10",
        "identifier": "0984782850"
       },
       {
        "type": "ISBN_13",
        "identifier": "9780984782857"
       }
      ],
     },
    }
   ]
  },
 ]
}    

I have a need to read the json using _.where, specifically search every item in the collection for the "identifier" value of "type": "ISBN_10". Then return the full json object aka {"items": [...]}.
Suppose req.params.id is the "identifier" value (i.e. 0984782850).
This piece of code is not working

var _ = require('underscore');
...
app.get('/api/books/:id', function(req, res) {
  var book = _.where(booksData.books.items[0].volumeInfo.industryIdentifiers[0], {identifier: req.params.id});
  res.json(book);
});

it is returning

TypeError: Cannot read property '0' of undefined at position 43  

The file has valid json, I have tried

var book = _.where(booksData.books, {items[0].volumeInfo.industryIdentifiers[0].identifier: req.params.id});

which also does not work

There is always one item in "items" and the ISBN_10 identifier is the first item in "industryIdentifiers" hence items[0].volumeInfo.industryIdentifiers[0].identifier

What am I doing wrong?

ridhwaans commented 5 years ago

works with array.find() (thanks acemarke)