2015-12-17 15 views
6

Ho il seguente oggetto contenente un array posts:filtro Lodash oggetto annidato

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" 
    }] 
    }] 
} 

Utilizzando Lodash, desidero estrarre tutti i messaggi con tags.slug di valore "case-studies". Attualmente sto provando il seguente senza fortuna:

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

Come farei questo?

risposta

8

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

Funziona! Grazie mille. – gosseti

0

risultato con sopra funzione utilizzando 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" 

sua deve restituire solo un oggetto all'interno di tag.