【问题标题】:Underscore.js where() function issue with searching json objectsUnderscore.js where() 函数与搜索 json 对象的问题
【发布时间】: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


【解决方案1】:

不要使用industryIdentifiers[1]。您要搜索整个 industryIdentifiers 数组,而不是单个对象。

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

你还需要books[0],因为books也是一个数组。

const booksData = {
 "books": [
  {
   "items": [
    {
     "id": "jD8iswEACAAJ",
     "volumeInfo": {
      "industryIdentifiers": [
       {
        "type": "ISBN_10",
        "identifier": "0984782850"
       },
       {
        "type": "ISBN_13",
        "identifier": "9780984782857"
       }
      ],
     },
    }
   ]
  },
 ]
};
var book = _.where(booksData.books[0].items[0].volumeInfo.industryIdentifiers, {identifier: "0984782850"})[0];
console.log(book);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

【讨论】:

  • 我已经尝试过这种更改,但我在回复中收到了[ ]。我应该得到 json [Object]
  • _.where 返回一个数组,因为可能有多个元素满足条件。如果您只需要第一个,请将其编入索引。
  • 我在末尾添加了[0],只返回第一个。
  • 你添加books[0]了吗?
  • items[0].volumeInfo.industryIdentifiers[0].identifier: 语法无效。
猜你喜欢
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-06
  • 2021-07-21
  • 1970-01-01
  • 1970-01-01
  • 2022-11-25
相关资源
最近更新 更多