2016-12-24 135 views
2
[ 
    { 
    "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 
    } 
] 

上面的示例陣列。按說明過濾JSON對象expressJS/UnderscoreJS

我想說只得到滿足某個查詢的對象。

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); 


}); 

這是如何工作的?如何在下劃線內部輸入一個函數作爲謂詞?

回答

0

你可以在普通的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)));

0

下劃線where取鍵:值對象作爲參數,而不是一個函數。如果你知道你想要的屬性,這很方便。

實例:

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

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

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

如果您的過濾條件較爲複雜,你需要指定一個謂詞,那麼你就必須使用filter,無論是直通下劃線或原生JS