当前位置:  开发笔记 > 编程语言 > 正文

Lodash过滤器嵌套对象

如何解决《Lodash过滤器嵌套对象》经验,为你挑选了1个好方法。

我有以下包含数组的对象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'})
  })
})

我该怎么做?



1> Andy..:

Lodash

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';
  });
});

推荐阅读
可爱的天使keven_464
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有