我有这个虚拟数据:
var data = [{
articles : [{
id : '0',
url : 'foo',
title : 'Foo',
body : 'some foo bar',
category : 'foo',
tags : [
'foo'
]
}, {
id : '1',
url : 'foo-bar',
title : 'Foo bar',
body : 'more foo bar',
category : 'foo',
tags : [
'foo', 'bar'
]
}, {
id : '2',
url : 'foo-bar-baz',
title : 'Foo bar baz',
body : 'more foo bar baz',
category : 'foo',
tags : [
'foo',
'bar',
'baz'
]
}]
}, {
users : [{
name: 'Admin'
}, {
name: 'User'
}]
}];
我有一个路由器,我只想从文章中请求匹配的文章ID:
// Grab single article
// http://127.0.0.1:3000/api/0
router.get('/:id', function(req, res) {
if(data.length <= req.params.id || req.params.id < 0) {
res.statusCode = 404;
return res.send('Error 404: No quote found');
};
var q = data[req.params.id];
res.json(q);
});
使用以下网址http://127.0.0.1:3000/api/0
返回文章组,但不返回第一篇文章。
感谢您的帮助!
答案 0 :(得分:1)
如果你真的想要匹配&#34; id&#34;而不仅仅是数组中的索引,你应该这样做:
var articles = data[0].articles;
var q = articles.filter(function (article) {
return article.id === req.params.id;
});
res.json(q[0]);
答案 1 :(得分:1)
外部数组中的第0个元素是包含所有文章的对象。首先,您需要深入查看文章数组:html
。然后,为了从数组中获取id属性与您需要的id号匹配的对象,您可以使用lo_dash库的data[0].articles
函数。 https://lodash.com/docs#find
电话会看起来像:_.find()