Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash filter nested object

I have the following object containing an array 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". 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?

like image 858
gosseti Avatar asked Dec 17 '15 12:12

gosseti


1 Answers

Lodash

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

Vanilla JS

var out = posts.posts.filter(function (el) {
  return el.tags.some(function (tag) {
    return tag.slug === 'case-studies';
  });
});
like image 76
Andy Avatar answered Sep 24 '22 18:09

Andy