【问题标题】:Lodash filter nested objectLodash过滤器嵌套对象
【发布时间】:2016-03-23 22:22:10
【问题描述】:

我有以下对象,其中包含一个数组 posts

var posts = {
  "posts": [{
    "id": 83,
    "title": "Onfido helps iCracked win customers’ confidence",
    "slug": "onfido-helps-icracked-win-customers-confidence",
    "tags": [{
      "id": 25,
      "slug": "case-studies"
    }, {
      "id": 10,
      "slug": "industry-news"
    }]
  }, {
    "id": 82,
    "title": "Machine learning makes banking more personal",
    "slug": "machine-learning-makes-banking-more-personal",
    "tags": [{
      "id": 10,
      "slug": "industry-news"
    }]
  }, {
    "id": 81,
    "title": "11 reasons to join Onfido",
    "slug": "ten-reasons-to-join-onfido",
    "tags": [{
      "id": 100,
      "slug": "our-expertise"
    }]
  }]
}

使用 Lodash,我想提取所有 tags.slug"case-studies" 的帖子。目前我一直在尝试以下方法,但没有成功:

_.filter(posts, function(post) {
  _.filter(post.tags, function(tag) {
    return _.where(tag, {'slug': 'case-studies'})
  })
})

我该怎么做?

【问题讨论】:

    标签: javascript arrays javascript-objects lodash


    【解决方案1】:

    洛达什

    var out = _.filter(posts.posts, function (post) {
      return _.some(post.tags, { 'slug': 'case-studies' });
    });
    

    原版JS

    var out = posts.posts.filter(function (el) {
      return el.tags.some(function (tag) {
        return tag.slug === 'case-studies';
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2013-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-11
      • 1970-01-01
      • 2020-07-28
      相关资源
      最近更新 更多