[
{
"id": 1,
"description": "Take out the trash",
"completed": false
},
{
"id": 2,
"description": "Get food tonight",
"completed": false
},
{
"id": 3,
"description": "Hit the gym",
"completed": true
}
]
上面的示例数组。
我想说的是只获取满足特定查询的对象。
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var _ = require('underscore');
app.get('/todos/query/:des', function (req, res){
var descriptionToFilter = req.params.des;
console.log(descriptionToFilter);
var filteredDesArr = _.where(todos,function(todo){
todo.description.contains(descriptionToFilter.toLowerCase());
});
res.send(filteredDesArr);
});
这是如何工作的?如何在下划线.where 内输入函数作为谓词?
最佳答案
下划线 where
将 key:value 对象作为其参数,而不是函数。如果您知道自己想要哪些属性,那就很方便了。
示例:
var Completed = _.where(todos,{completed:true});
vargymCompleted = _.where(todos,{completed:true,description:"去健身房"})
where
返回包含指定属性的所有元素,findWhere
返回第一个匹配元素。
如果您的过滤条件更复杂,并且需要指定谓词,那么您必须使用 filter
,通过下划线或原生 JS
关于javascript - 按描述过滤 JSON 对象 Express JS/Underscore JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41311396/