简体   繁体   English

Lodash过滤器嵌套对象

[英]Lodash filter nested object

I have the following object containing an array posts : 我有以下包含数组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"
    }]
  }]
}

Using Lodash, I'd like to extract all posts with tags.slug of value "case-studies" . 使用Lodash,我想用tags.slug "case-studies"值的tags.slug提取所有帖子。 Currently I've been trying the following with no luck: 目前我一直在尝试以下运气:

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

How would I do this? 我该怎么做?

Lodash Lodash

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

Vanilla JS 香草JS

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

Result with above function using loadash: 使用loadash的上述函数的结果:

 0: Object
 id: 83
 slug: "onfido-helps-icracked-win-customers-confidence"
 tags: Array[2]
        0: Object 
           id: 25
           slug: "case-studies",
        1: Object
           id: 10
           slug: "industry-news"

   //while the expected one is :
    0: Object
       id: 83
       slug: "onfido-helps-icracked-win-customers-confidence"
       tags: Array[1]
           0: Object 
           id: 25
           slug: "case-studies"

its should return only one object inside tags. 它应该只返回标签内的一个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM