如何匹配包含“tags”数组中匹配值的每个文章对象,例如,如果我只想列出包含“foo”和“bar”关键字的文章?
[
{
"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" ]
}
]
}
]
以下是我的Express应用程序中的路由器,它调用此JSON文件:
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
});
});
});
答案 0 :(得分:1)
查看标签是否在数组中。
var q = articles.filter(function (article) {
var tagInArray = false;
article.tags.forEach(function(tag){
if(tag === req.params.tag){
tagInArray = true;
}
});
return tagInArray;
});
IndexOf
答案 1 :(得分:0)
标签位于数组
中 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;
}
});