0

How I can match every articles object which are containing the matching values from the "tags" array, for example if I want to only list the articles which containing "foo" and "bar" keywords?

[
  {
    "articles": [
      {
        "_id": "0",
        "body": "This is a test article 1.",
        "tags": [ "foo", "bar" ]
      },
      {
        "_id": "2",
        "body": "This is a test article 2.",
        "tags": [ "baz", "bam" ]
      },
      {
        "_id": "4",
        "body": "This is a test article 4.",
        "tags": [ "foo", "bar", "baz", "bam" ]
      }
    ]
  }
]

Here is the router in my Express app which is calling this JSON file:

router.get('/:tag', function (req, res, next) {
  fsAsync(function(err, data) {
    var articles = data[0].articles.reverse();

    var q = articles.filter(function (article) {
      return article.tags === req.params.tag;
    });

    var json = [{ articles: q }];

    // I want the results here
    console.log(json);

    res.render('blog-tag', {
      layout: 'main',
      data: json
    });
  });
});

2 Answers 2

1

See if the tag is in the array.

var q = articles.filter(function (article) {
  var tagInArray = false;
  article.tags.forEach(function(tag){
      if(tag === req.params.tag){
         tagInArray = true;
      }
  });
  return tagInArray;
});

IndexOf

Sign up to request clarification or add additional context in comments.

Comments

0

Tags are in Array

 var q = articles.filter(function (article) {
 for (var i = 0;i<article.tags.length;i++){
 if(article.tags[i] === req.params.tag)
 return article.tags === req.params.tag;
 }
});

1 Comment

This code seems more simple, but unfortunately not working for me. Returning only [] in the console. :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.