Search code examples
javascriptarraysnode.jsunderscore.jsghost-blog

Using Underscore to delete an object using an embedded array


Sorry my title sucks, I couldn't think of a better way to explain my issues. I'm hacking on Ghost blog attempting to create sections on my site by filtering out posts with certain tags. Handlebars cant handle what I need to do on the client-side so I'm digging around in the server-side controllers attempting to accomplish this. I found controllers/frontend.js and have been attempting to modify the formatPageResponse function.

I tried something like this but it's obviously not working. Tags is it's own array within the each object of the posts array.

posts = _.without(posts, _.findWhere(posts.tags, {'name': 'News'}));


Solution

  • I'm going to assume your posts array looks like this:

    [ { title: "Some Post", tags: { "name": "News" } }, ... ]
    

    I would simply use a filter:

    posts = _.filter(posts, function(post){ 
        return !_.any(post.tags, function(tag){
           return tag.name === 'News' 
        } 
    });