【发布时间】:2019-08-10 00:45:56
【问题描述】:
我有一个 json 集合作为 {"books": [{...}, ... ]} 存储在一个文件中。 "books" 是一个 json 对象列表,其中每个对象都是一本书。例如:
{
"books": [
{
"items": [
{
"id": "jD8iswEACAAJ",
"volumeInfo": {
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "0984782850"
},
{
"type": "ISBN_13",
"identifier": "9780984782857"
}
],
},
}
]
},
]
}
我需要使用 _.where 读取 json,专门搜索集合中的每个项目以查找 "type": "ISBN_10" 的 "identifier" 值。然后返回完整的 json 对象,即 {"items": [...]}。
假设 req.params.id 是 "identifier" 值(即 0984782850)。
这段代码不工作
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);
});
它正在返回
TypeError: Cannot read property '0' of undefined at position 43
文件有合法的json,我试过了
var book = _.where(booksData.books, {items[0].volumeInfo.industryIdentifiers[0].identifier: req.params.id});
这也不起作用
"items" 中总是有一个项目,ISBN_10 标识符是"industryIdentifiers" 中的第一个项目,因此items[0].volumeInfo.industryIdentifiers[0].identifier
我做错了什么?
*编辑:我试过industryIdentifiers,但回复是[ ]
【问题讨论】:
-
你能用javascript filter命令吗?
booksData.books.filter ( book => book.items.filter( item => item.volumeInfo.industryIdentifiers.type === 'ISBN_10').length > 0).length > 0);
标签: javascript json list underscore.js