javascript - 按描述过滤 JSON 对象 Express JS/Underscore JS

标签 javascript json node.js underscore.js

[
  {
    "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/

相关文章:

java - 使用 MoXY 以 XML 和 JSON 形式对列表进行合理表示

java - 加载错误 LibGDX/Scene2d

javascript - 通过JavaScript从json中获取所有键的值

node.js - 如何在nodejs中向未链接到DNS但在hosts文件中注册的url发出http请求?

node.js - 我无法在 Mac OS X 10.10.3 上安装 ionic

javascript - addClass ('x' ) 总是返回 false...?

javascript - Angular Directive(指令)

javascript - 如何在 JavaScript 中将字符串转换为 float ?

javascript - 如何获取 jPlayer 中歌曲当前播放的时间?

node.js - Nodejs :Array data not added in mongodb