【问题标题】:Filter by description JSON object expressJS/UnderscoreJS按描述 JSON 对象过滤 expressJS/UnderscoreJS
【发布时间】:2016-12-24 07:44:02
【问题描述】:
[
  {
    "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);


});

这是如何工作的?如何在 underscore.where 中输入函数作为谓词?

【问题讨论】:

    标签: javascript json node.js underscore.js


    【解决方案1】:

    下划线 where 将 key:value 对象作为其参数,而不是函数。如果您知道自己想要哪些属性会很方便。

    例子:

    var completed = _.where(todos,{completed:true});

    var gymCompleted = _.where(todos,{completed:true,description:"Hit the gym"})

    where 返回所有包含指定属性的元素,findWhere 返回第一个匹配的元素。

    如果您的过滤条件更复杂,并且您需要指定谓词,那么您必须使用filter,通过下划线或本机 JS

    【讨论】:

      【解决方案2】:

      您可以在带有正确回调的纯 Javascript 中使用 Array#filter

      function byCompleted(item) {
          return item.completed;
      }
      
      function byId(id) {
          return function (item) {
              return item.id === id;
          };
      }
      
      
      var data = [{ 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 }];
      
      console.log(data.filter(byCompleted));
      console.log(data.filter(byId(2)));

      【讨论】:

        猜你喜欢
        • 2019-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-09
        • 2014-11-19
        • 2019-10-30
        相关资源
        最近更新 更多