【问题标题】:Searching through an array of objects in node在节点中搜索对象数组
【发布时间】:2017-03-26 01:09:31
【问题描述】:

我有一个对象数组,每个对象都包含以下数据:

我有一个节点路由,它拉入一个标签,然后搜索它。现在我输入的任何东西都返回-1。如果标签与查询匹配,我如何获得修改后的数组。

同样,此刻,我输入的任何内容,包括有效标签,都返回 -1。

那时,我会使用修改后的数组转身,将其注入到模板中,如您所见。

router.get('/search/:tag', function(req, res) {
  const tag = req.params.tag;
  shopify.article.list(86289414)
  .then(function (response) {
    response.reverse();

    index = response.indexOf(response.filter(function(item) {
      return item.tags == tag
  }) )

  console.log(index);

    var data = {
      articles: index.map((article) => {
        return {
          author: article.author,
          id: article.id,
          html: article.body_html,
          tags: article.tags,
          date: moment(article.published_at).format("Do MMM YYYY"),
          slug: article.handle,
        } // return
      }) // map
    } // data

      res.json(data);

  }) // then
    .catch(err => console.log(err) )
});

有什么更好的方法来做到这一点?

谢谢!

附:我浏览了lodash,找不到任何东西。我对 lodash 的方式持开放态度。

【问题讨论】:

  • 请不要发布真正是对象文字的图像。以文本形式发布。
  • Array.filter() 返回一个数组。 indexOf(returnedArray) 将始终为 -1,因为返回的数组只是原始数组的子集。

标签: javascript arrays node.js object express


【解决方案1】:

我用下面的代码解决了这个问题。

response = response.filter(function(item) {
     return item.tags.indexOf(tag) > -1;
   });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 2011-04-07
    • 2015-09-12
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多